如何在 MySQL 中强制执行两个相似字段的唯一组合
我有一组由 id 定义的点,以及一个定义这些点之间连接的数据库表:
[point1, point2]
现在我可以强制 point1 和 point2 的排列是唯一的。因此只有 1 个条目,其中 point1 = x 和 point2 = y。但我想要独特的组合,这意味着如果存在带有 point1 = x 和 point2 = y 的条目,则不可能获得带有 point1 的条目= y 和 point2 = x。
是否可以为此配置表,或者我是否必须通过代码强制执行此操作?
I have a set of points, defined by an id, and a database table which defines a connection between those points:
[point1, point2]
Now I can enforce that permutations of point1 and point2 are unique. So there's only 1 entry where point1 = x and point2 = y. But I want unique combinations, meaning that if there's a entry with point1 = x and point2 = y, it shouldn't be possible to get an entry with point1 = y and point2 = x.
Is it possible to configure the table for this or do I have to enforce this through code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个结构也许适合你?
正确
This structure should work for you maybe?
CORRECT
我将通过结合
(point1, point2)
上的唯一索引point1 <= point2
(即反转如果违反该条件则触发)。I'd approach this with a combination of
(point1, point2)
point1 <= point2
(i.e., reverse the two values in the trigger if they violate that condition).我建议搜索该组合,例如
SELECT id WHERE pointx = 'value' AND pointy = 'value';
查找该组合。$numrows = mysql_num_rows($result);
if($numrows !> 0){
//用这些点做任何事情。
}
I would suggest search for that combo like
SELECT id WHERE pointx = 'value' AND pointy = 'value';
look for that combo.$numrows = mysql_num_rows($result);
if($numrows !> 0){
//do what ever with the points.
}
此触发器将完成这项工作:
我只是通过计算条件
(p1 = new.p1 AND p2 = new.p2) 返回的记录数来测试是否存在您尝试插入的值的组合) OR (p1 = new.p2 AND p2 = new.p1)
,如果该数字不同于 0,我将调用一个不存在的过程以使触发器失败并避免插入新记录。This trigger will do the job:
I just test if there's a combination of the values you're trying to insert by counting the number of records that are returned by the condition
(p1 = new.p1 AND p2 = new.p2) OR (p1 = new.p2 AND p2 = new.p1)
, and if that number is different from 0 I call a non-existant procedure to make the trigger fail and avoid the insertion of the new record.