MySQL外键具有多个(有条件的)可能的值 [英] MySQL foreign key having multiple (conditional) possible values

查看:176
本文介绍了MySQL外键具有多个(有条件的)可能的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的想法是在一个表中使用两个条目(一个包含被引用的表名和一个包含该表中的关键字)来引用其他几个表中的一个。



<表

$ p $ CREATE TABLE people

peopleid SMALLINT UNSIGNED auto_increment,
name VARCHAR(40)NOT NULL,
prevname VARCHAR(40),
角色ENUM('Teacher','Mentor','Administrator'),
roleid SMALLINT UNSIGNED

注意:Teacher and Mentor是表格。如果此人是管理员,则RoleID将为空。



我希望RoleID成为引用在角色字段中引用任何表的外键。如何做到这一点?

解决方案

最好的办法是为角色和人员提供一个单独的表格。这将提供一个规范化和关系模型。


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?

解决方案

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

这篇关于MySQL外键具有多个(有条件的)可能的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆