在用户开始私有(private)聊天(两个成员之间,而不是群聊)之前,我想检查是否已经存在仅由这两个成员组成的聊天。如果他们删除了聊天记录,当他们再次向同一用户发送消息时,我希望它与旧聊天记录合并,而不是为相同的两个成员启动重复的聊天记录。
这是我的结构
`chats` table
id created_time
1 [TIMESTAMP]
2 [TIMESTAMP]
`chats.parties` table
id chat_id member_id invited_by
1 1 1 0 // creator of chat
2 1 2 1
3 1 3 1
4 2 1 0
5 2 2 1
按 chat_id
分组,但仅返回包含 member_id=1
和 member_id=2
行的结果;不多也不少。
在上表中,仅返回 chat_id=2
行,因为 chat_id=1
包含第三个成员。
这可以用原始 SQL 实现吗?我不想在 php 中循环,因为需要一段时间进行大量聊天。
最佳答案
这里有两种不同的方法来获得您正在寻找的结果:
-- using conditional aggregation
select chat_id from chat_parties
group by chat_id
having sum(case when member_id = 1 then 1 else 0 end) > 0
and sum(case when member_id = 2 then 1 else 0 end) > 0
and sum(case when member_id not in (1, 2) then 1 else 0 end) = 0
-- using a correlated subquery
select chat_id from chat_parties c1
where member_id in (1,2)
and not exists (
select 1 from chat_parties where chat_id = c1.chat_id and member_id not in (1,2)
)
group by chat_id having count(distinct member_id) = 2
更改表名称以适合您的实际设置。
关于mysql - Group By MySQL 查询返回带有参数的特定结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34933631/