外來鍵是一個(或數個)指向另外一個表格主鍵的欄位。外來鍵的目的是確定資料的參考完整性(referential integrity)。換言之,只有被准許的資料值才會被存入資料庫內。
舉例來說,假設我們有兩個表格:一個 CUSTOMER 表格,裡面記錄了所有顧客的資料;另一個 ORDERS 表格,裡面記錄了所有顧客訂購的資料。在這裡的一個限制,就是所有的訂購資料中的顧客,都一定是要跟在 CUSTOMER 表格中存在。在這裡,我們就會在 ORDERS 表格中設定一個外來鍵,而這個外來鍵是指向 CUSTOMER 表格中的主鍵。這樣一來,我們就可以確定所有在 ORDERS 表格中的顧客都存在 CUSTOMER 表格中。換句話說,ORDERS表格之中,不能有任何顧客是不存在於 CUSTOMER 表格中的資料。
這兩個表格的結構將會是如下:
CUSTOMER 表格
| 欄位名 |
性質 |
| SID |
主鍵 |
| Last_Name |
|
| First_Name |
|
ORDERS 表格
| 欄位名 |
性質 |
| Order_ID |
主鍵 |
| Order_Date |
|
| Customer_SID |
外來鍵 |
| Amount |
|
在以上的例子中,ORDERS 表格中的 customer_SID 欄位是一個指向 CUSTOMERS 表格中 SID 欄位的外來鍵。
以下列出幾個在建置 ORDERS 表格時指定外來鍵的方式:
MySQL:
CREATE TABLE ORDERS
(Order_ID integer,
Order_Date date,
Customer_SID integer,
Amount double,
Primary Key (Order_ID),
Foreign Key (Customer_SID) references CUSTOMER(SID));
Oracle:
CREATE TABLE ORDERS
(Order_ID integer primary key,
Order_Date date,
Customer_SID integer references CUSTOMER(SID),
Amount double);
SQL Server:
CREATE TABLE ORDERS
(Order_ID integer primary key,
Order_Date datetime,
Customer_SID integer references CUSTOMER(SID),
Amount double);
以下的例子則是藉著改變表格架構來指定外來鍵。這裡假設 ORDERS 表格已經被建置,而外來鍵尚未被指定:
MySQL:
ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(sid);
Oracle:
ALTER TABLE ORDERS
ADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(sid);
SQL Server:
ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(sid);
下一頁:SQL CREATE VIEW
網站導引 |
其他資源
Copyright 1999-2009 1keydata.com. 版權所有
|