簡體   English   中英

mysql加入group by和order by

[英]Mysql join with group by and order by

我正在使用此mysql查詢

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

在消息表中,它顯示消息ID最早的消息,我想返回最新消息。 但它顯示最舊的消息。 我該如何解決。

首先嘗試ORDER BY,然后再嘗試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`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM