In PostgreSQL, a foreign key constraint requires only LINKS?

I read the docs for PostgreSQL constraints because I wanted to see how to define foreign keys. In my examples

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

I do not see FOREIGN KEYanywhere; however, in a few other questions (for example, how to add “when deleting cascading restrictions? ), I saw a recording FOREIGN KEY. Do I need to write FOREIGN KEYor only need to be used REFERENCES?

+4
source share
2 answers

That's a good question.

You will notice a limitation FOREIGN KEYin the doc examples related to DDL constraints. I prefer to use the restriction FOREIGN KEYas indicated in example 3. below.

/ -:

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
);

- 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

+4

.

foreign key :

  • .
  • .
  • , .

: .

+5

All Articles