CREATE TABLE m (
id INTEGER(11) NOT NULL AUTO_INCREMENT,
u_from INTEGER(11) NOT NULL,
u_to INTEGER(11) NOT NULL,
PRIMARY KEY USING BTREE (id)
) ENGINE=InnoDB
AUTO_INCREMENT=8 CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'
;
INSERT INTO `m` (id, u_from, u_to) VALUES
(1,7,1),
(2,7,1),
(3,7,1),
(4,7,1),
(5,1,7),
(6,1,4),
(7,4,1);
COMMIT;
select
max(id) id,
if(u_from = 1, concat('TO ', u_to), concat('FROM ', u_from)) last_msg,
u_from,
u_to
from m
where u_from = 1 or u_to = 1
group by if(u_from = 1, u_to, u_from)
order by id