mysql - Group By MySQL 查询返回带有参数的特定结果

标签 mysql

在用户开始私有(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=1member_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/

相关文章:

php - 如何将 PDO 用于特定于数据库的功能?

mysql - 如何显示刚刚发生的 MySQL 警告?

javascript - 查询在 mysql 中显示一个值,但在 HTML 页面中显示为 null

java - 当多个java客户端访问数据库时确保数据完整性

php - MYSQL 中的 ORDER BY 条件使用函数返回

mysql - 如何获取mysql每5分钟查询数据的总和(列)和最后一个索引值

mysql - 使用 fullCalendar 从 mysql 获取今天的事件

mysql - 如何在 Oracle 中设置固定时间分钟和秒与当前小时

php - PHP和MySql上传大小问题

php - Laravel 4 - 将多个值插入数据透视表