如何让这个mysql查询显示一个DISTINCT行?

时间:2016-03-23 03:53:40

标签: mysql

SELECT DISTINCT message_group.group_id, messages.*
FROM messages
LEFT JOIN message_group ON message_group.group_id = messages.group_id
WHERE message_group.username = 'admin'
OR message_group.recipients = 'admin'
ORDER BY messages.id DESC

即使我指定了DISTINCT message_group.group_id

,它也是如何显示数据的

为什么这样做?如何让它只显示一个group id

更多参考:https://stackoverflow.com/questions/36167801/how-to-order-message-groups-messages-just-like-imessage

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT message_group.group_id, messages.*
FROM messages INNER JOIN
    (SELECT 
        MAX(`timestamp`) AS latest,
        group_id
     FROM messages
     GROUP BY group_id) m2 
     ON messages.group_id = m2.group_id AND messages.`timestamp` = m2.`timestamp`
LEFT JOIN message_group ON message_group.group_id = messages.group_id
WHERE message_group.username = 'admin'
OR message_group.recipients = 'admin'
ORDER BY messages.id DESC