gpt4 book ai didi

mysql - 如何根据唯一的子行查找父行?

转载 作者:行者123 更新时间:2023-11-29 06:04:03 24 4
gpt4 key购买 nike

我的架构(MySQL、InnoDb):

Conversation
------------
id (int)

User
----
id (int)

UserConversation
----------------
user_id (int, FK)
conversation_id (int, FK)

只是将用户映射到对话(多对多)。

现在,在我创建 user1 和 user2 之间的新对话之前,我想检查数据库中是否已经存在这两个用户之间的对话。

所以我要选择:

  • 与用户 1、用户 2 的对话

但不是:

  • 与用户 1、用户 2、用户 3 的对话
  • 与 User1 的对话
  • 与用户 1、用户 3 的对话
  • 等等

换句话说:我的目标是防止在用户组之间创建重复的对话。 Yii2 ActiveRecord 还是纯 SQL 查询是如何实现的?

最佳答案

您可以在where 子句中使用一系列存在/不存在条件来确定对话 是否仅在特定用户之间进行。唯一的缺点是您需要为每个用户添加一个新的 exists 条件:

select c.id
from conversation c
where exists (select 1 from userconversations uc where uc.conversation_id=c.id and uc.user_id=1)
and exists (select 1 from userconversations uc where uc.conversation_id=c.id and uc.user_id=2)
and not exists (select 1 from userconversations uc where uc.conversation_id=c.id and uc.user_id not in (1,2))

另一种方法是比较记录数:

select conversation_id, count(if(user_id in (1,2),1,null)) as in_user, count(*) as all_user
from userconversations uc
group by conversation_id
having in_user=2 and all_user=2

如果列表中有超过 2 个用户,此查询不需要 where 子句中的其他条件,但可能比 exists 版本慢,因为条件计数。您需要测试这两种解决方案,看看哪种更适合您。

关于mysql - 如何根据唯一的子行查找父行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42927456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com