我正在阅读关于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) );
这些示例来自文档.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。