Ini mengasumsikan id
adalah kolom kenaikan otomatis:
SELECT MAX(id) AS id
FROM pms
WHERE id_to = 1 OR id_from = 1
GROUP BY (IF(id_to = 1, id_from, id_to))
Dengan asumsi Anda memiliki id_from
dan id_to
diindeks, variasi ini kemungkinan besar akan berkinerja lebih baik karena MySQL tidak tahu apa yang harus dilakukan dengan OR:
SELECT MAX(id) AS id FROM
(SELECT id, id_from AS id_with
FROM pms
WHERE id_to = 1
UNION ALL
SELECT id, id_to AS id_with
FROM pms
WHERE id_from = 1) t
GROUP BY id_with
Berikut cara mendapatkan pesan untuk id tersebut:
SELECT * FROM pms WHERE id IN
(SELECT MAX(id) AS id FROM
(SELECT id, id_from AS id_with
FROM pms
WHERE id_to = 1
UNION ALL
SELECT id, id_to AS id_with
FROM pms
WHERE id_from = 1) t
GROUP BY id_with)