两个字段及其相反的唯一约束
问题如下,
我的数据库中有一个友谊表,该友谊表有两个指向用户表的外键。
我想在两个外键上设置一个唯一键,这样我就不会重复,但我想要更多,我希望如果用户A添加用户B,那么B将无法添加A,我想要表中只有一行代表A和B之间的友谊。
有没有办法从数据库服务器添加这样的约束?
到目前为止,我一直在代码中保留此约束。
The problem is the following,
I have a table of friendships in my database, the friendship table has two foreign keys to the users table.
I want to set a unique key on the two foreign keys so that I will have no duplicates, but I want more, I want that if user A added user B, then B won't be able to add A, and I want to have only one row in the table that represents the friendship between A and B.
Is there any way to add such a constraint from the database server?
Until now I have maintained this constraint in my code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您需要添加一个触发器来检查您所描述的业务规则,并在发现冲突时回滚事务。在不同的数据库中,其语法可能有所不同,但在 SQL Server 中,它是
Yes you need to add a trigger that checks the business rule you have described and rolls back the transaction if it finds a conflict. The syntax for this might be different in different databases, but in SQL server it would be
您可以在
( LEAST(friend1,friend2), GREATEST(friend1,friend2) )
上添加唯一约束。确切的措辞可能取决于所使用的 RDBMS。You can add a unique constraint on
( LEAST(friend1,friend2), GREATEST(friend1,friend2) )
. The exact wording may depend on theRDBMS
being used.