我正在阅读关于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
?
答案 0 :(得分:5)
评论时间有点长。
您主要在以下三种情况下使用foreign key
:
第四个原因也是合理的:因为本地编码标准要求使用显式约束。
答案 1 :(得分:5)
这是一个很好的问题。
您会注意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,
product_no integer REFERENCES products (product_no),
quantity integer
);
OR
子表 - Ex2
请注意,父表和子表应具有相同的列名,以使用此简明表示法。
CREATE TABLE orders (
order_id integer PRIMARY KEY,
product_no integer REFERENCES products,
quantity integer
);
OR
子表 - 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