如何将两个主键用于一个外键?

时间:2014-02-17 08:12:33

标签: mysql relational-database entity-relationship relationship

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)
   -> );

1 个答案:

答案 0 :(得分: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