按照SQL-92標準輸入值:
一外鍵(FK)可能引用PRIMARY KEY
或UNIQUE CONSTRAINT
。在PRIMARY KEY
的情況下,所引用的列可以從外鍵聲明中省略,例如,以下三個都是有效的:
CREATE TABLE Department (Department INTEGER NOT NULL PRIMARY KEY, ...);
CREATE TABLE Worker (dept INTEGER REFERENCES Department, ...);
CREATE TABLE Department (Department INTEGER NOT NULL PRIMARY KEY, ...);
CREATE TABLE Worker (dept INTEGER REFERENCES Department (dept), ...);
CREATE TABLE Department (Department INTEGER NOT NULL UNIQUE, ...);
CREATE TABLE Worker (dept INTEGER REFERENCES Department (dept), ...);
下是無效的:
CREATE TABLE Department (Department INTEGER NOT NULL UNIQUE, ...);
CREATE TABLE Worker (dept INTEGER REFERENCES Department, ...);
...因爲涉及的外鍵所引用的列必須聲明。
當聲明一個簡單的(單柱)FK在線的FOREIGN KEY
關鍵字如上刪去。
的複合(多列)不能在線進行聲明和一個簡單的FK不需要在在線聲明:在這些情況下,引用列需要(S)AND的FOREIGN KEY
關鍵字(規則對於參考列保持與前面所述相同),例如這裏只舉幾個例子:
CREATE TABLE Department (Department INTEGER NOT NULL PRIMARY KEY, ...);
CREATE TABLE Worker (dept INTEGER, FOREIGN KEY (dept) REFERENCES Department, ...);
CREATE TABLE Department (Department INTEGER NOT NULL UNIQUE, ...);
CREATE TABLE Worker (dept INTEGER, FOREIGN KEY (dept) REFERENCES Department (dept), ...);
CREATE TABLE DepartmentHistory
(
dept INTEGER NOT NULL,
dt DATE NOT NULL,
PRIMARY KEY (dt, dept),
...
);
CREATE TABLE Worker
(
dept INTEGER NOT NULL,
dept_dt DATE NOT NULL,
FOREIGN KEY (dept_dt, dept) REFERENCES DepartmentHistory,
...
);
你的worker表應該有dept_id,而不是dept。用於'引用'和'外鍵'的語法可能會從SQL實現到SQL實現有點不同。 –
一些實現可能讓你使用'部門引用部門',但在這些情況下,你可能想刪除'整數' –