如下图, 计划实现 :按照 parent_code 分组, 取组中code最大值所在的整条记录,如红色部分。(类似hive中: row_number() over(partition by))
select c.* from ( select a.*, (@i := case when @key_i=parent_code then @i+1 else 1 end) as sort_num,(@key_i:=parent_code) as tmp from my_test a, (SELECT @i := 0,@key_i:=‘‘) b order by parent_code,code desc) c where c.sort_num=1;
个人理解, mysql 运行顺序: from >> where >> order by >> select .
以下部门应该有助于理解mysql中变量的概念。
1.=========================================================================================================
仅按照code排序,加序号sort_num效果如下:
select (@i := @i + 1) as sort_num, a.* from my_test a, (SELECT @i := 0) b order by code;
2.=========================================================================================================
仅按parent_code分组,按照code排序,加序号.
select a.*, (@i := case when @key_i=parent_code then @i + 1 else 1 end) as sort_num,(@key_i:=parent_code) as tmp from my_test a, (SELECT @i := 0,@key_i:=‘‘) b order by parent_code,code desc;
参考链接 :https://blog.csdn.net/zzhhoubin/article/details/79839610
https://www.cnblogs.com/CharlieLau/p/6737243.html
https://blog.csdn.net/u011728683/article/details/78594070
原文地址:https://www.cnblogs.com/andylhc/p/10216626.html
时间: 2024-12-12 12:50:34