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

m0m*_*eni 5 sql postgresql

我正在阅读关于PostgreSQL约束的文档,因为我想看看如何定义外键.在他们的例子中

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer REFERENCES products (product_no),
    quantity integer
);
Run Code Online (Sandbox Code Playgroud)

我什么都没看到FOREIGN KEY; 但是,在其他几个堆栈溢出问题中(如何添加"on delete cascade"约束?例如)我已经看过了FOREIGN KEY写的.是否有必要写FOREIGN KEY或只需要使用REFERENCES

Gor*_*off 5

评论有点长.

foreign key主要在三种情况下使用:

  • 您有另一个表的多键引用.
  • 您想要命名外键引用.
  • 您想要添加其他功能,例如级联删除.

第四个原因也是合理的:因为本地编码标准需要使用显式约束.

  • @Bohemian:MySQL不支持"内联"外键.它们被解析但是(默默地!)被忽略了 (2认同)

zed*_*xus 5

这是一个很好的问题.

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

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

父表

CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);
Run Code Online (Sandbox Code Playgroud)

儿童桌 - Ex1

内联外键约束没有提到 FOREIGN KEY

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer REFERENCES products (product_no),
    quantity integer
);
Run Code Online (Sandbox Code Playgroud)

要么

儿童桌 - Ex2

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

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer REFERENCES products,
    quantity integer
);
Run Code Online (Sandbox Code Playgroud)

要么

儿童桌 - Ex3

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

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer,
    quantity integer,
    FOREIGN KEY (product_no) REFERENCES products (product_no),
);
Run Code Online (Sandbox Code Playgroud)

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

CREATE TABLE t1 (
  a integer PRIMARY KEY,
  b integer,
  c integer,
  FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)
);
Run Code Online (Sandbox Code Playgroud)

这些示例来自文档.

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