两个字段及其相反的唯一约束

发布于 2024-08-04 00:26:13 字数 192 浏览 7 评论 0原文

问题如下,

我的数据库中有一个友谊表,该友谊表有两个指向用户表的外键。

我想在两个外键上设置一个唯一键,这样我就不会重复,但我想要更多,我希望如果用户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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

动次打次papapa 2024-08-11 00:26:13

是的,您需要添加一个触发器来检查您所描述的业务规则,并在发现冲突时回滚事务。在不同的数据库中,其语法可能有所不同,但在 SQL Server 中,它是

  Create Trigger trig_StopRecipFriendships
  for Insert, Update On Friendships
  As
    If Exists (Select * From Friendships F1
                 Join Friendships F2  
                   On F1.UserA = F2.UserB
                      And F1.UserB = F2.UserA)
     Begin
         Rollback Transaction
         Raiserror ('These Users are already friends', 16,1)
     End

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

  Create Trigger trig_StopRecipFriendships
  for Insert, Update On Friendships
  As
    If Exists (Select * From Friendships F1
                 Join Friendships F2  
                   On F1.UserA = F2.UserB
                      And F1.UserB = F2.UserA)
     Begin
         Rollback Transaction
         Raiserror ('These Users are already friends', 16,1)
     End
喜爱纠缠 2024-08-11 00:26:13

您可以在 ( 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 the RDBMS being used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文