簡體   English   中英

使用沒有 FOREIGN KEY 的 REFERENCES 是否仍會創建外鍵?

[英]Does using REFERENCES without FOREIGN KEY still create a foreign key?

我之前做過一些 SQL 但沒有加載。 如果在創建表時使用它而不使用 FOREIGN KEY,我對 REFERENCES 的作用有點困惑,例如

author_id INTEGER REFERENCES users(id),

相對於...

FOREIGN KEY (author_id) REFERENCES users(id)

如果這些不同,有什么區別? 如果它們相同,應該首選哪種形式?

第一個:

author_id INTEGER REFERENCES users,

...是以下的簡寫:

author_id INTEGER REFERENCES users (id),

...這是以下的簡寫:

FOREIGN KEY (author_id) REFERENCES users (id)

...這又是 SQL 標准的簡寫:

CONSTRAINT <constraint-name> 
FOREIGN KEY (<column>) 
REFERENCES <table>(<columns>)

第一個涵蓋了基本的、最常見的情況,並且很簡潔。 好的。

現在,完整的語法涵蓋了所有可能變化的一般情況。 考慮例如:

  • 復合外鍵

     book_id int not null, chapter_id int not null, constraint fk1 foreign key (book_id, chapter_id) references chapter (book_id, chapter_id)

    由於它是復合鍵,因此不能在列級別指定,而是在表級別指定。

  • 分叉外鍵

     owner_id int not null, constraint fk2 foreign key (owner_id) references person (id), constraint fk3 foreign key (owner_id) references company (id)

    在這種情況下,同一列指向多個表。 想象一下這個結合了復合外鍵......

通常,您會偶爾看到復合鍵,並且很少分叉外鍵。 大多數時候,您會看到簡單的外鍵,這就是速記語法如此有用的原因。

如果您只使用 REFERENCES PostgreSQL 創建一個外鍵:

postgres=# create table parent(id int primary key);
CREATE TABLE

postgres=# create table child(id int primary key, fk int references parent);
CREATE TABLE

postgres=# \d child;
               Table "public.child"
 Column |  Type   | Collation | Nullable | Default 
--------+---------+-----------+----------+---------
 id     | integer |           | not null | 
 fk     | integer |           |          | 
Indexes:
    "child_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "child_fk_fkey" FOREIGN KEY (fk) REFERENCES parent(id)

postgres=# 

從語法的角度來看,REFERENCES 用於列級別,而 FOREIGN KEY 用於表級別。

請參閱外鍵和引用鍵有什么區別?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM