Postgres 中主键的定义方式有什么不同吗?
我想知道所有这些是否完全相同或者是否存在一些差异。
方法 1:
CREATE TABLE testtable
(
id serial,
title character varying,
CONSTRAINT id PRIMARY KEY (id)
);
方法:2
CREATE TABLE testtable
(
id serial PRIMARY KEY,
title character varying,
);
方法 3:
CREATE TABLE testtable
(
id integer PRIMARY KEY,
title character varying,
);
CREATE SEQUENCE testtable_id_seq
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO MINVALUE
CACHE 1;
ALTER SEQUENCE testtable_id_seq OWNED BY testtable.id;
更新: 我在网上发现一些内容说,通过使用原始序列,您可以为主键预分配内存,如果您计划进行数千次插入,这会有所帮助在下一分钟。
I am wondering if all these are exactly the same or if there is some difference.
Method 1:
CREATE TABLE testtable
(
id serial,
title character varying,
CONSTRAINT id PRIMARY KEY (id)
);
Method: 2
CREATE TABLE testtable
(
id serial PRIMARY KEY,
title character varying,
);
Method 3:
CREATE TABLE testtable
(
id integer PRIMARY KEY,
title character varying,
);
CREATE SEQUENCE testtable_id_seq
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO MINVALUE
CACHE 1;
ALTER SEQUENCE testtable_id_seq OWNED BY testtable.id;
Update: I found something on the web saying that by using a raw sequence you can pre-allocate memory for primary keys which helps if you plan on doing several thousand inserts in the next minute.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下看看;删除第二个和第三个“variing”后的尾随“,”,以便它们运行,执行每个,然后
在每个之后执行:,您可以看到会发生什么。然后放下桌子并移至下一张桌子。它看起来像这样:
First 和 Second 几乎相同,只是创建的主键的名称不同。在第三种情况下,当您插入数据库时,不再填写序列。您需要首先创建序列,然后创建表,如下所示:
获得与第二个看起来相同的内容。唯一的好处是您可以使用 CACHE 指令来预先分配一些序列号。这可能会造成足够大的资源消耗,您需要减少争用。但在这种情况发生之前,您需要每秒(而不是每分钟)执行数千次插入。
Try it and see; remove the trailing "," after "varying" on the second and third so they run, execute each of them, then do:
after each one and you can see what happens. Then drop the table and move onto the next one. It will look like this:
First and second are almost identical, except the primary key created is named differently. In the third, the sequence is no longer filled in when you insert into the database. You need to create the sequence first, then create the table like this:
To get something that looks the same as the second one. The only upside to that is that you can use the CACHE directive to pre-allocate some number of sequence numbers. It's possible for that to be a big enough resource drain that you need to lower the contention. But you'd need to be doing several thousand inserts per second, not per minute, before that's likely to happen.
方法 1 和方法 2 之间没有语义差异。
方法 3 也非常相似 - 这是使用串行时隐式发生的情况。然而,当使用serial时,postgres也会记录sequence对表的依赖关系。因此,如果删除在方法 1 或 2 中创建的表,该序列也会被删除。
No semantic difference between method 1 and method 2.
Method 3 is quite similar, too - it's what happens implicitly, when using serial. However, when using serial, postgres also records a dependency of sequence on the table. So, if you drop the table created in method 1 or 2, the sequence gets dropped as well.