SELECT data.* FROM
(SELECT MAX(sendtime) AS sendtime
FROM data
WHERE 1 IN (sender,receiver)
GROUP BY IF (1 = sender,receiver,sender)) AS latest
LEFT JOIN data ON latest.sendtime = data.sendtime AND 1 IN (data.sender, data.receiver)
GROUP BY IF (1 = data.sender,data.receiver,data.sender)
Jag rekommenderar att du använder unikt sekvens-id i din tabell för att undvika extern GROUP BY
.Om du har ökande unika message_id
(dvs. större message_id
motsvarar senare sendtime
), skulle frågan vara mycket enklare:
SELECT data.* FROM
(SELECT MAX(message_id) AS message_id
FROM data
WHERE 1 IN (sender,receiver)
GROUP BY IF (1 = sender,receiver,sender)) AS latest
LEFT JOIN data USING(message_id)