[英]Unique constraint across two columns
I have a table called friends with the following structure: 我有一个名为friends的表,其结构如下:
id
user_id
friend_id
and I want the rows to be unique so for example: 我希望这些行是唯一的,例如:
1, 6, 12
2, 6, 12
would break! 会坏! I've achieved this with:
ALTER TABLE friends ADD UNIQUE INDEX user_id_friend_id (user_id, friend_id);
我是通过以下方式实现的:
ALTER TABLE friends ADD UNIQUE INDEX user_id_friend_id (user_id, friend_id);
BUT I also want the following to not be possible 但我也想下面来是不可能的
1, 6, 12
2, 12, 6
How do I do that? 我怎么做? I tried doing the same statement but with the fields reversed but it didn't work... Any ideas?
我尝试做同样的声明,但是字段颠倒了,但是没有用...有什么想法吗?
You could use triggers to ensure that user_id <= friend_id
, this with the unique constraint will achieve what you want. 您可以使用触发器来确保
user_id <= friend_id
,这具有唯一性约束将实现您想要的。 You'll need an insert and update trigger like this: 您将需要一个插入和更新触发器,如下所示:
Create Trigger
Friends_ins_check
Before Insert On
Friends
For Each Row
Begin
If new.user_id > new.friend_id Then
Set @temp = new.user_id;
Set new.user_id = new.friend_id;
Set new.friend_id = @temp;
End If;
End
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.