PostgreSQL 外來鍵關聯操作

2021-10-24 13:04:53 字數 2744 閱讀 4356

乙個外來鍵約束指定一列(或一組列)中的值必須匹配出現在另乙個表中某些行的值。我們說這維持了兩個關聯表之間的引用完整性。注意,乙個從表外來鍵所引用的主表 column 必須是乙個主鍵或者是被唯一約束所限制的。這意味著主表被引用的列總是擁有乙個索引(位於主鍵或唯一約束之下的索引),因此在其上進行的乙個引用行是否匹配的檢查將會很高效。

# 主表

create

table products (

product_no integer

primary

key,

name text

, price numeric);

# 從表

create

table orders (

order_id integer

primary

key,

product_no integer

references products (product_no)

, quantity integer);

# 從表簡寫,因為缺少宣告主表的列名,所以將主表的主鍵作為引用。

create

table orders (

order_id integer

primary

key,

product_no integer

references products,

quantity integer);

# 定義多個 column 組成的外來鍵,要求被約束列(外來鍵)的數量和型別應該匹配被引用列(主鍵)的數量和型別。

create

table t1 (

a integer

primary

key,

b integer

, c integer

,foreign

key(b, c)

references other_table (c1, c2));

# many2many,新增乙個中間表 order_items 來引用兩個主表 products 和 orders。

create

table products (

product_no integer

primary

key,

name text

, price numeric);

create

table orders (

order_id integer

primary

key,

shipping_address text,.

..);

create

table order_items (

product_no integer

references products,

order_id integer

references orders,

quantity integer

,primary

key(product_no, order_id));

# on delete/update 的聯動操作型別,例如:限制刪除/更新、級聯刪除/更新。

# restrict 和 no action 具有相同的語義,兩者本質不同在於 no action 允許關聯檢查推遲到事務的最後,而 restrict 則會馬上報錯。

# set null 主表在 on delete/update 時,設定從表外來鍵為 null。

# set default 主表在 on delete/update 時,設定從表外來鍵為 default(預設值)。

create

table products (

product_no integer

primary

key,

name text

, price numeric);

create

table orders (

order_id integer

primary

key,

shipping_address text,.

..);

create

table order_items (

product_no integer

references products on

delete

restrict

,# 限制刪除

order_id integer

references orders on

delete

cascade

,# 級聯刪除

quantity integer

,primary

key(product_no, order_id)

);

格式:

alter

table 從表名 add

constraint 外來鍵約束名 foreign

key(從表的外來鍵)

references 主表名 (主表的主鍵)

;

注意:如果要給乙個已存在的表新增 on delete cascade 的外來鍵約束,需要如下步驟:

刪除已存在的外來鍵約束。

新增乙個 on delete cascade 的外來鍵約束。

格式:

alter

table 從表名 drop

constraint 從表的外來鍵約束名;

關聯 外來鍵問題

外來鍵問題 外來鍵一定是每個表的主鍵關聯問題 兩個表之間有聯絡,是通過外來鍵的設定模型中如果有外來鍵和多對多字段,建立的時候外來鍵必須首先繫結,然後儲存,才能新增多對多字段。relationships 主要有三類 many to one,many to many,one to one class s...

MySQL 外來鍵關聯策略

eg.乙個使用者可有擁有多個訂單,乙個訂單只能屬於乙個使用者,一對多,在tb order中使用外來鍵user id關聯tb user的id。當刪除 更新tb user中的主鍵時,與之關聯的tb order要受到影響,比如 tb user中的一條記錄 1chy abcd tb order中一條記錄,1...

mysql 中不能關聯外來鍵 mysql 外來鍵關聯

mysql 外來鍵關聯 什麼是外來鍵 外來鍵是乙個特殊的索引,用於關聯兩個表,只能是指定內容。如我將新建乙個daka的表,然後將此表的class id 與另外乙個class的表的cid欄位關聯 class表 create table class cid int 11 not null auto in...