MySQL Distinct / Group by,打破了这个问题

时间:2017-08-30 12:37:39

标签: mysql sql group-by distinct instant-messaging

所以,我试图做的是检索所有" initial"的列表。一个人在其消息窗口中看到的消息

这是表结构

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

它们都没有返回我想要的东西,这是所有唯一的thread_id,其中发送者或接收者等于" bTP5n"

免责声明:虚假数据用于此问题

2 个答案:

答案 0 :(得分:1)

如果您在第二个联合查询中使用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

答案 1 :(得分:0)

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