MySQL Distinct / Group by,这个让我头疼

MySQL Distinct / Group by, breaking my head with this one

所以,我想要做的是检索一个人在他们的消息 window

中看到的所有 "initial" 消息的列表

这是table结构

thread_id | sender | receiver | message | date | sender_deleted | sender_received | read
xRdaQ     | bTP5n  | lCBNA    | hello!  | date | 0              | 0               | 
xRdaQ     | lCBNA  | bTP5n    | hey!    | date | 0              | 0               | 
1T4xR     | bTP5n  | An03R    | hhi     | date | 0              | 0               | 

到目前为止我尝试过的查询:

select * from messages where sender = 'bTP5n'
union select * from messages where receiver = 'bTP5n'
group by conversation_id

而且我仍然得到具有相同 thread_id

的两行

与这一个查询相同:

select * from messages where sender = 'bTP5n'
union select * from messages where receiver = 'bTP5n'
group by conversation_id order by date desc

他们都未能return我想要的,这是唯一的thread_id发送者或接收者等于"bTP5n"

免责声明:此问题使用了虚拟数据

如果你在第二个联合查询中使用group by那么它只适用于第二个查询,如果你想在所有结果中应用那么你必须在所有结果之外写group by。 尝试以下查询:

select * from 
(select * from messages where sender = 'bTP5n' 
 union 
 select * from messages where receiver = 'bTP5n' 
) 
as a group by conversation_id order by date desc

只要对原始数据使用统计计算函数,就需要GROUP BY子句。你的例子不是你的情况