MySQL-带ORDER DESC的GROUP BY无法正常工作 [英] MySQL - GROUP BY with ORDER DESC not working
本文介绍了MySQL-带ORDER DESC的GROUP BY无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的以下查询有问题.
SELECT id, user_id, cloth_id FROM `items` GROUP BY user_id ORDER BY id desc LIMIT 3
我想要具有group by
的最新记录,但不知何故它显示了旧记录.
I want the latest records with group by
but somehow its showing old records.
我也经历过 MySQL-按DESC排序的分组方式但未按预期工作.
I have also gone through MySQL - Group by with Order by DESC but not working as expected.
推荐答案
尝试一下:
SELECT i.id, i.user_id, i.cloth_id FROM
(
SELECT max(id) as id, user_id FROM `items` GROUP BY user_id
) temp
LEFT JOIN `items` i on i.user_id = temp.user_id AND i.id = temp.id
temp
中,您会获得每个具有最新ID的用户.
在i
中,您将获得该组合的cloth_id
in temp
you get each user with the latest id.
in i
you get the cloth_id for that combination
这篇关于MySQL-带ORDER DESC的GROUP BY无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文