MySQL GROUP BY / ORDER BY issue with flat messages table / threads

白昼怎懂夜的黑 提交于 2019-12-06 08:10:38

Here's an idea: take the UNION of the following two queries, then get the maximum dates from the result.

SELECT id,to_uid AS other_party,time_added FROM messages WHERE from_uid = '1'

SELECT id,from_uid AS other_party,time_added FROM messages WHERE to_uid = '1'

When you do the following:

SELECT MAX(time_added),other_party
FROM (SELECT id,to_uid AS other_party,time_added FROM messages WHERE from_uid = '1'
      UNION
      SELECT id,from_uid AS other_party,time_added FROM messages WHERE to_uid = '1'
     ) MyMessages
GROUP BY other_party

You will get the most recent time associated with a message sent to each person that user '1' is corresponding with. Then you can join the results of that to the original messages table to get what you want:

SELECT Messages.*
FROM (SELECT MAX(time_added) AS MaxTime,other_party
      FROM (SELECT id,to_uid AS other_party,time_added FROM messages WHERE from_uid = '1'
            UNION
            SELECT id,from_uid AS other_party,time_added FROM messages WHERE to_uid = '1'
           ) MyMessages
      GROUP BY other_party
     )
     JOIN Messages
     ON (Messages.time_added = MyMessages.MaxTime AND
          (Messages.to_uid = MyMessages.other_party AND Messages.from_uid = '1' OR
           Messages.from_uid = MyMessages.other_party AND Messages.to_uid = '1')
        )

Try this - I think it gives you what you are looking for more simply and efficiently.

SELECT latest_time = MAX(a.time_added, b.time_added)
FROM messages a, messages b

LEFT JOIN messages a1
    ON a1.from_uid = a.from_id

-- find the case where the following doesn't exist
-- so you know there is nothing after b1
LEFT JOIN messages a2
    ON a2.from_uid = a.from_id
    AND a2.time_added > a1.time_added

LEFT JOIN messages b1
    ON b1.to_uid = b.to_id

LEFT JOIN messages b2
    ON b2.to_uid = b.to_id
    AND b2.time_added > b1.time_added

WHERE a.from_id = '1'
    AND b.to_id = '1'
    AND c1.id IS NULL
    AND c2.id IS NULL

ORDER BY a.time_added DESC

Ok, after comments - if id is autoincrement use it instead of message time. But you have propoer condition to ensure that messages will not be delivered to wrong persons.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!