简体   繁体   English

“串行”列是否自动成为PostgreSQL中的主键?

[英]Is a 'serial' column automatically a primary key in PostgreSQL?

I've created the following table in Postgres... 我在Postgres中创建了下表...

create table printq (
   model varchar(20),
   session integer,
   timestamp timestamp DEFAULT now(),
   id serial);

It seems to do exactly what I need it to... it auto-increments the id column, when I clear the table using truncate "RESTART IDENTITY" it resets the sequence (which is why I rebuilt the table in the first place -- the id column used to not restart upon truncation) 它似乎正是我需要它...它自动递增id列,当我使用truncate“RESTART IDENTITY”清除表时,它重置序列(这就是我首先重建表的原因 - 用于在截断时不重新启动的id列)

Anyway, when I do a \\d on the table, I don't see anything about a primary key. 无论如何,当我在桌面上做一个\\ d时,我看不到关于主键的任何信息。

Table "public.printq"
  Column   |            Type             |                      Modifiers                      
-----------+-----------------------------+-----------------------------------------------------
 model     | character varying(20)       | 
 session   | integer                     | 
 timestamp | timestamp without time zone | default now()
 id        | integer                     | not null default nextval('printq_id_seq'::regclass)

Three questions: 三个问题:

  • Is the ID column already a primary key since it auto-increments, or not? ID列是否已成为主键,因为它自动递增?

  • If not, why would this table need a primary key, since it seems to be working fine? 如果没有,为什么这个表需要一个主键,因为它似乎工作正常? I know basically every table is supposed to have a primary key, but why exactly? 我知道基本上每个表都应该有一个主键,但为什么呢?

  • Finally, would the \\d command tell me if this table had a primary key? 最后,\\ d命令会告诉我这个表是否有主键吗? If not, what would tell me? 如果没有,会告诉我什么?

  1. No, use id serial primary key for that. 不,使用id serial primary key
  2. Well, a table doesn't actually "need" a primary key. 好吧,表实际上并不“需要”主键。 It can live without PK, it can live without an autoincrementing field, it can contain duplicate rows all right. 它可以在没有PK的情况下生存,它可以在没有自动增量字段的情况下生存,它可以包含重复的行。 But in relational theory (on top of which SQL is built) each relation (ie table) is a set (in mathematical sense) of rows. 但是在关系理论(在其上构建SQL)上,每个关系(即表)都是行的集合(在数学意义上)。 So duplicate rows are not allowed, they are simply not possible in sets. 因此不允许重复行,它们在集合中是不可能的。 And hence each relation has a field (or several fields) which has unique values for all the relation. 因此,每个关系都有一个字段(或几个字段),它具有所有关系的唯一值。 Such field can be used to uniquely identify a row, and one of possible unique keys is called a primary key. 这样的字段可以用于唯一地标识行,并且可能的唯一密钥之一被称为主键。 Such a key is usually very useful for identifying the rows, that's why tables are supposed to have them. 这样的键通常对于识别行非常有用,这就是表应该有它们的原因。 But technically they are not required. 但从技术上讲,它们并不是必需的。
  3. Yes, it will. 是的,它会的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM