Dette forudsætter id
er en kolonne med automatisk stigning:
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))
Forudsat at du har id_from
og id_to
indekseret, vil denne variant højst sandsynligt fungere bedre, fordi MySQL ikke ved, hvad de skal gøre med en 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
Sådan får du beskederne til disse id'er:
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)