gpt4 book ai didi

MySQL选择具有公共(public)列的行

转载 作者:行者123 更新时间:2023-11-29 02:22:03 25 4
gpt4 key购买 nike

我有一个名为 conversation_user 的表,其中包含 usersconversations 之间的关系(基本上它存储了参与对话的用户)。

它是这样的:

----------------------------
| id | conversation | user |
----------------------------
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 4 |
| 4 | 3 | 2 |
| 5 | 3 | 3 |
| 6 | 4 | 1 |
| 7 | 4 | 2 |
| 8 | 4 | 3 |
----------------------------

我想编写一个查询,给定参与对话的用户的用户 ID,它返回对话 ID(如果有)。

Example:

User IDs: [1, 2] => Conversation ID: 1
User IDs: [2, 1, 3] => Conversation ID: 4

这是我到目前为止能够实现的:

SELECT conversation FROM conversation_user WHERE user IN (1, 2) GROUP BY conversation HAVING count(*) = 2

当然这个查询会返回:

---------------
| conversation|
---------------
| 1|
| 4|
---------------

最佳答案

您正在寻找完全匹配。因此,(1, 2) 匹配对话 4。

为此,您不能使用 where 子句进行过滤。相反:

SELECT conversation
FROM conversation_user
GROUP BY conversation
HAVING count(*) = 2 AND
sum(user in (1, 2)) = count(*);

= 2 是您要查找的参与者数量。

关于MySQL选择具有公共(public)列的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30104248/

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