Answer the question
In order to leave comments, you need to log in
How to select only those users with whom there are messages?
Once again I ask for help! I am implementing a message system on the site and everything would be fine - but for some reason the developer decided to show all users in the list of dialogs at once - even those to whom neither we wrote nor they wrote to us. I would really like to fix this (the issue was created there a long time ago - but the author disappeared ().
message table - actually only two fields are of interest - from whom and to whom
`messages` (
`id` int(11) NOT NULL,
`from_id` int(11) DEFAULT NULL,
`whom_id` int(11) NOT NULL,
`message` varchar(750) NOT NULL,
`status` int(11) DEFAULT '0',
`is_delete_from` int(11) DEFAULT '0',
`is_delete_whom` int(11) DEFAULT '0',
`created_at` int(11) NOT NULL,
`updated_at` int(11) NOT NULL
)
SELECT
`usr`.`id`,
`usr`.`username` AS `username`,
`msg`.`cnt` AS `cnt_mess`,
`msg_`.`cnt_` AS `cnt_mess_all`
FROM
`user` `usr`
LEFT JOIN
(
SELECT
`from_id`,
count(id) AS `cnt`
FROM
`messages`
WHERE
(
`status` = 1
)
AND
(
`whom_id` = 9
)
GROUP BY
`from_id`
)
`msg`
ON usr.id = msg.from_id
LEFT JOIN
(
SELECT
`from_id`,
`whom_id`,
count(id) AS `cnt_`
FROM
`messages`
WHERE
(
`from_id` = 9
)
OR
(
`whom_id` = 9
)
GROUP BY
`from_id`
)
`msg_`
ON usr.id = msg_.from_id
or usr.id = msg_.whom_id
WHERE
`usr`.`id` != 9
ORDER BY
`msg`.`cnt` DESC,
`usr`.`username` DESC
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question