postgresql PostgreSQL复制命令生成主键id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7920777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 23:09:44  来源:igfitidea点击:

PostgreSQL copy command generate primary key id

postgresql

提问by user373201

I have a CSV file with two columns: city and zipcode. I want to be able to copy this file into a PostgreSQL table using the copycommand and at the same time auto generate the idvalue.

我有一个包含两列的 CSV 文件:城市和邮政编码。我希望能够使用该copy命令将此文件复制到 PostgreSQL 表中,同时自动生成该id值。

The table has the following columns: id, city, and zipcode.

该表具有以下的列:idcity,和zipcode

My CSV file has only: cityand zipcode.

我的 CSV 文件只有:cityzipcode.

回答by mu is too short

The COPY commandshould do that all by itself if your table uses a serialcolumn for the id:

COPY命令应该做的所有的本身,如果你的表使用serial列的id

If there are any columns in the table that are not in the column list, COPY FROM will insert the default values for those columns.

如果表中有任何不在列列表中的列,COPY FROM 将插入这些列的默认值。

So you should be able to say:

所以你应该能够说:

copy table_name(city, zipcode) from ...

and the idwill be generated as usual. If you don't have a serialcolumn for id(or a manually attached sequence), then you could hook up a sequence by hand, do your COPY, and then detach the sequence.

并且id将照常生成。如果您没有serial用于id(或手动附加序列)的列,那么您可以手动连接序列,进行 COPY,然后分离序列。