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

时间:2015-05-28 02:47:13

标签: sql postgresql

我正在阅读关于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

2 个答案:

答案 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