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)
外部のGROUP BY
を避けるために、テーブルで一意のシーケンスIDを使用することをお勧めします 。一意のmessage_id
をインクリメントする場合 (つまり、より大きなmessage_id
後のsendtime
に対応します )、クエリははるかに簡単になります:
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)