Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Mysql与group by和order by的连接_Php_Mysql_Sql_Join_Greatest N Per Group - Fatal编程技术网

Php Mysql与group by和order by的连接

Php Mysql与group by和order by的连接,php,mysql,sql,join,greatest-n-per-group,Php,Mysql,Sql,Join,Greatest N Per Group,我正在使用这个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` =

我正在使用这个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的消息,我想返回最新消息。但它显示了最古老的信息。如何解决此问题。

请先尝试按顺序,然后仅按分组

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`

每个组的最大n没有帮助?是的,我知道有子查询解决方案,但子查询解决方案针对不同的表,而不是主表,现在只需关注“different”表。我使用另一个查询来解决这个问题,从线程中获取最后一条消息,并替换arrayyes中的第一条消息,但我不会停止思考这个问题。