简体   繁体   English

MySQL:是否可以对两个不同的表列创建外键?

[英]MySQL: Is it possible to make a foreign key to two different table-columns?

I have a table (a) which should have a column "user_id", which is a foreign key of some other table (b) OR (c). 我有一个表(a),该表应具有一列“ user_id”,这是其他表(b)或(c)的外键。 So wether it points to table b or c (only one, not both). 因此,它指向表b或c(仅一个,而不是两个)。

Is this even possible in MySQL? 在MySQL中甚至可能吗? Best thing I can come up with is following (but as you can see, I have "user_id" twice in my "a"-table, which is not very nice, since one of the two values will always be empty. 我能想到的最好的方法是跟踪(但是正如您所看到的,我的“ a”表中有两次“ user_id”,这不是很好,因为两个值之一始终为空。

在此处输入图片说明

Thank you very much! 非常感谢你!

Hi this is called Polymorphic Associations and you cannot enforce it using MySql foreign key constraints. 嗨,这被称为多态关联,您不能使用MySql外键约束来强制实施它。

in order to have either userId_a null or user_id_b null you can create a check constraint 为了使userId_a为null或user_id_b为null,您可以创建检查约束

CONSTRAINT CHECK (user_id_a IS NOT NULL OR user_id_b IS NOT NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM