目的:查询 category_id 分组下,最新id的 good_name
表结构及数据:goods表
id category_id good_name
1 1 3OFUM5jU6w
2 1 2eAHE9yL8S
3 2 QBH6IP9mYg
4 3 fhrnLyFlyu
5 4 er7D2fVjcz
6 5 sY4p0tSmpB
7 6 KrUxx9uhSy
8 7 cLhlDJXoIS
9 8 YdvDIUeGtR
10 9 l23e1HyyIj
11 10 yJNNPXbWzt
12 1 2222222222
解决方案分析
基础查询:
select max(id) cate_maxid from goods group by category_id
方案:取出最新纪录后再联合查询【可行】
select t1.id, t1.good_name, t1.category_id from goods t1 join (
select max(id) cate_maxid, category_id from goods group by category_id
) as t2 on t1.id = t2.cate_maxid and t2.category_id = t1.category_id;
以下方案不可行。分组后只能取到其他字段升序排序的第一条纪录。
方案一:只分组后取数据【不可行,分组未排序】
select id, good_name, category_id from goods
group by category_id
;
方案二:排序得到结果集后再分组【不可行,分组对排序后结果集无效】
select t2.id, t2.good_name, t2.category_id from (
select * from goods order by id desc
) t2 GROUP BY t2.category_id;
方案三:与方案二雷同,排序得到结果集后再联合查询并分组【不可行,分组对排序后结果集无效】
select t1.id, t1.good_name, t1.category_id from goods t1 join (
select * from goods order by id desc
) as t2 on t1.id = t2.id group by t2.category_id;
方案四:与方案三雷同,不过调换排序结果集的位置【不可行 ,分组对排序后结果集无效】
select t1.id, t1.good_name, t1.category_id from (
select * from goods order by id desc
) as t2 join goods t1 on t1.id = t2.id group by t2.category_id;
方案五:与方案二雷同,排序得到的结果集放到 in 查询中再分组【不可行 ,分组对排序后结果集无效】
select t1.id, t1.good_name, t1.category_id from goods t1
where id in (select id from goods order by id desc) group by t1.category_id;
20200424 补充:在网上找到具体原因的解释了:实际是跟 mysql 版本有关:https://bugs.mysql.com/bug.php?id=80131