Question

I am using this mysql query

SELECT `p`.`id` AS product_id, `p`.`title` , `i`.`image` , `u`.`user_username` , `m`.`id` AS message_id, `m`.`date` , `m`.`from` , `m`.`to` , `m`.`message` , `m`.`read`
FROM (`messages` AS m)
JOIN `products` AS p ON `m`.`product_id` = `p`.`id`
JOIN `users` AS u ON `m`.`from` = `u`.`user_id`
JOIN `product_images` AS i ON `p`.`id` = `i`.`product_id`
WHERE `i`.`type` = 'FRONT'
AND (m.to = '1171' OR m.from = '1171)
GROUP BY `m`.`therad_user` , `m`.`product_id`
ORDER BY `m`.`id` DESC

In message table it shows message with oldest message id, I want to return latest message. but it show oldest message. how I solve this.

Was it helpful?

Solution

Try ORDER BY first, then only GROUP BY

SELECT * FROM
(
SELECT `p`.`id` AS product_id, `p`.`title` , `i`.`image` , `u`.`user_username` , `m`.`id` AS message_id, `m`.`date` , `m`.`from` , `m`.`to` , `m`.`message` , `m`.`read`
FROM (`messages` AS m)
JOIN `products` AS p ON `m`.`product_id` = `p`.`id`
JOIN `users` AS u ON `m`.`from` = `u`.`user_id`
JOIN `product_images` AS i ON `p`.`id` = `i`.`product_id`
WHERE `i`.`type` = 'FRONT'
AND (m.to = '1171' OR m.from = '1171)
ORDER BY `m`.`id` DESC
) tmp
GROUP BY `m`.`therad_user` , `m`.`product_id`
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top