-5
mysql> CREATE TABLE guests (
    -> id int(11) NOT NULL AUTO_INCREMENT, 
    -> first_name varchar(55) DEFAULT NULL, 
    -> last_name varchar(55) DEFAULT NULL, 
    -> email varchar(100) DEFAULT NULL, 
    -> role_type int(4) DEFAULT 4, 
    -> start_date date, 
    -> expiry_date date, 
    -> reason blob, 
    -> added_by int(4) NOT NULL REFERENCES super_admins(id), 
    -> password_digest varchar(255) DEFAULT NULL, 
    -> remember_token date DEFAULT NULL, 
    -> primary key(id), 
    -> CONSTRAINT fk_guests FOREIGN KEY(added_by) REFERENCES super_admins(id), 
    -> CONSTRAINT fk_guests1 FOREIGN KEY (added_by) REFERENCES admin(id) 
    ->); 
+0

你的問題不明確。但從你的問題的標題:你不能有兩個主鍵定義主鍵是什麼 –

+0

@AlmaDo我想他試圖用不同表中的2個主鍵創建一個組合鍵。 – J2D8T

+0

CREATE TABLE超級管理員( ID INT(11)NOT NULL AUTO_INCREMENT, 如first_name VARCHAR(55)DEFAULT NULL, 姓氏VARCHAR(55)DEFAULT NULL, 電子郵件VARCHAR(100)DEFAULT NULL, role_type INT(4)默認值0 , PRIMARY KEY(id) ); – user1900814

回答

1

它被稱爲多態關係(關聯)。你不能有一個列(added_by你的情況),同時引用兩個父表。但是你可以做什麼才能使用外鍵約束是有兩個可爲空的列added_by_super_adminadded_by_admin,其中只有一列將保存每個記錄的值。

CREATE TABLE guests 
(
    id INT(11) NOT NULL AUTO_INCREMENT, 
    first_name VARCHAR(55) DEFAULT NULL, 
    last_name VARCHAR(55) DEFAULT NULL, 
    email VARCHAR(100) DEFAULT NULL, 
    role_type INT(4) DEFAULT 4, 
    start_date DATE, 
    expiry_date DATE, 
    reason blob, 
    added_by_super_admin INT(4) NULL, 
    added_by_admin INT(4) NULL, 
    password_digest VARCHAR(255) DEFAULT NULL, 
    remember_token DATE DEFAULT NULL, 
    PRIMARY KEY(id), 
    CONSTRAINT fk_guests FOREIGN KEY (added_by_super_admin) REFERENCES super_admins(id), 
    CONSTRAINT fk_guests1 FOREIGN KEY (added_by_admin) REFERENCES admin(id) 
); 

然後在查詢中,你可以做

SELECT ... 
     COALESCE(s.id, a.id) added_by_id, 
     COALESCE(s.name, a.name) added_by_name, 
     ... 
    FROM guests g LEFT JOIN super_admins s 
    ON g.added_by_super_admin = s.id LEFT JOIN admin 
    ON g.added_by_admin = a.id 
+0

添加此訪客帳戶鏈接,在您的發佈查詢上方顯示此錯誤消息 錯誤1005(HY000):無法創建表'backjobs.guests'( errno:150) – user1900814