加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在PostgreSQL中,外键约束只需要REFERENCES吗?

发布时间:2020-12-13 18:07:29 所属栏目:百科 来源:网络整理
导读:我正在阅读关于PostgreSQL约束的 docs,因为我想看看如何定义外键.在他们的例子中 CREATE TABLE orders ( order_id integer PRIMARY KEY,product_no integer REFERENCES products (product_no),quantity integer); 我没有在任何地方看到FOREIGN KEY;但是,在其
我正在阅读关于PostgreSQL约束的 docs,因为我想看看如何定义外键.在他们的例子中
CREATE TABLE orders (
    order_id integer PRIMARY KEY,product_no integer REFERENCES products (product_no),quantity integer
);

我没有在任何地方看到FOREIGN KEY;但是,在其他几个堆栈溢出问题(例如How to add “on delete cascade” constraints?)中,我看到了FOREIGN KEY写的.是否有必要写FOREIGN KEY或是否只需要使用REFERENCES?

这是一个很好的问题.

您将注意到doc中与DDL约束相关的示例中的FOREIGN KEY约束.我更喜欢使用FOREIGN KEY约束,如下面的例3所示.

你可以用不同的方式做外键/引用:

父表

CREATE TABLE products (
    product_no integer PRIMARY KEY,name text,price numeric
);

儿童桌 – Ex1

内联外键约束而不提及FOREIGN KEY

CREATE TABLE orders (
    order_id integer PRIMARY KEY,quantity integer
);

要么

儿童桌 – Ex2

请注意,父表和子表应具有相同的列名以使用此简明表示法.

CREATE TABLE orders (
    order_id integer PRIMARY KEY,product_no integer REFERENCES products,quantity integer
);

要么

儿童桌 – Ex3

请注意,我们在此处明确使用FOREIGN KEY关键字.

CREATE TABLE orders (
    order_id integer PRIMARY KEY,product_no integer,quantity integer,FOREIGN KEY (product_no) REFERENCES products (product_no),);

如果需要约束多个字段,FOREIGN KEY约束也可以这样写:

CREATE TABLE t1 (
  a integer PRIMARY KEY,b integer,c integer,FOREIGN KEY (b,c) REFERENCES other_table (c1,c2)
);

这些示例来自文档.

SQL小提琴示例:http://sqlfiddle.com/#!15/dd2d6

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读