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
SELECT `user_id`, MAX(`id`)
FROM (
SELECT `id`, `fsender_id` AS `user_id`
FROM `messages`
WHERE `ssender_id` = :iserId
UNION SELECT `id`, `ssender_id`
FROM `messages`
WHERE `fsender_id` = :iserId
) AS `t`
GROUP BY `user_id`
select min(id), case when fsender_id = 1 then ssender_id
when ssender_id = 1 then fsender_id end other_id
from users
where fsender_id = 1 or ssender_id = 1
group by other_id
Find more questions by tags MySQL
Indeed, the result is the one that I want)
I understand that it's weird, but I need the first message, so refined, everything works)))
Thank you very much ! - gaylord.DuBuq commented on April 19th 20 at 12:42
1. If you have such data, the result is not quite correct:
2. You need to take into account not only the id = 1:
u_from = 1 or u_to = 1
, but other id, we need a more complex grouping. - afton.Boyle74 commented on April 19th 20 at 12:45