简体   繁体   English

MySQL为多个表中的列添加唯一约束?

[英]MySQL add unique constraint on columns from multiple tables?

Here's an example for what I am looking to do : 这是我要做的事情的一个例子:

I have 3 tables : 我有3张桌子:

  • Villages (id, name) 村庄(身份证,姓名)
  • Households (id, village_id) 家庭(id,village_id)
  • Persons (first_name, last_name, household_id) 人员(first_name,last_name,household_id)

I would like to make sure there isn't 2 persons who have the same first name and last name in the same village. 我想确保没有2个人在同一个村庄拥有相同的名字和姓氏。

Basically I would like to do something of that sort : 基本上我想做那样的事情:

ALTER TABLE persons 
 ADD UNIQUE (first_name, last_name, households.village_id 
            WHERE household_id=households.id)

Is there a way to do something like that ? 有没有办法做那样的事情?

You can't really do that directly, but if this is to store real-world data it is theoretically possible for two people with identical name to live within a village, so this may not be the best idea? 你不能直接这样做,但如果这是为了存储真实世界的数据,理论上可能有两个名字相同的人住在一个​​村庄里,所以这可能不是最好的主意吗?

If you insist on going down this route then I recommend using a STORED PROCEDURE to handle inserts to this table taking in arguments such as user name and village. 如果你坚持沿着这条路走,那么我建议使用一个STORED PROCEDURE来处理这个表的插入,接受用户名和村庄等参数。 The stored procedure could then do a SELECT prior to INSERT to check for conflicts. 然后,存储过程可以在INSERT之前执行SELECT以检查冲突。 This would take the place of any INSERT queries. 这将取代任何INSERT查询。 UPDATEs would also need handling via procedure to prevent clashes. UPDATE还需要通过程序处理以防止冲突。

I think there is no simple way to do that. 我认为没有简单的方法可以做到这一点。

You might wanna try creating triggers on before insert/update and throw error on your custom condition. 您可能想尝试在插入/更新之前创建触发器并在自定义条件上抛出错误。 But it is highly dependant on your MySQL version: prior to version 5.5, I believe there is no correct way to raise an error - usually people use hacks like calling non-existent procedures. 但它高度依赖于您的MySQL版本:在5.5版之前,我认为没有正确的方法来引发错误 - 通常人们会使用黑客来调用不存在的程序。 But if you are on version >5.5 you can use SIGNAL statement: http://dev.mysql.com/doc/refman/5.5/en/signal.html 但是如果你的版本> 5.5,你可以使用SIGNAL语句: http//dev.mysql.com/doc/refman/5.5/en/signal.html

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

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