MySQL foreign key having multiple (conditional) possible values

我的未来我决定 提交于 2019-12-14 03:18:58

问题


My idea is to use two entries (one containing the referenced table name and one containing the key in that table) in one table to reference one of several other tables.

The relevant parts of the table:

CREATE TABLE people 
  ( 
     peopleid SMALLINT UNSIGNED auto_increment, 
     name     VARCHAR(40) NOT NULL, 
     prevname VARCHAR(40), 
     role     ENUM('Teacher', 'Mentor', 'Administrator'), 
     roleid   SMALLINT UNSIGNED 
  ) 

Note:Teacher and Mentor are tables. If the person is an administrator, RoleID would be null.

I want the RoleID to be the foreign key referencing what ever table is referenced in the Role field. How do I do that?


回答1:


Your best bet is to have a separate table for roles and people. This will provide a normalized and relational model.




回答2:


SQL isn't designed to do that. You will need separate foreign keys if you want to link to separate tables.



来源:https://stackoverflow.com/questions/14653893/mysql-foreign-key-having-multiple-conditional-possible-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!