最近工作中用到mysql,发现mysql和Oracle差别挺大的,其不像Oracle中存在丰富的分析函数(开窗函数),如rank(),lag(),leaf()等,只能用变量来获取以便达到分析函数的效果,具体使用方法如下:
eg:
想通过member id进行分组,获取每个用户最新首次操作的时间,实际上就是根据member id分组后取出最早的一条,但是由于没有分析函数不能快速实现,只能用这种方式操作。
select t2.member_id, t2.created_time time from (select t1.id,
t1.member_id,
t1.created_time,
@rownum := @rownum + 1,
if(@member_id = t1.member_id, @rank := @rank + 1, @rank := 1) as rank,
@member_id := t1.member_id
from (select id, member_id, created_time
from t01_et_open_account_step_log
where step = 310
order by member_id asc, created_time asc) t1,
(select @rownum := 0, @member_id := null, @rank := 0) t0) t2 where t2.rank = 1; ORDER BY t2.member_id asc
运行结果:
也许直接看代码不够清晰,先执行里层
select t1.id,
t1.member_id,
t1.created_time,
@rownum := @rownum + 1,
if(@member_id = t1.member_id, @rank := @rank + 1, @rank := 1) as rank,
@member_id := t1.member_id
from (select id, member_id, created_time
from t01_et_open_account_step_log
where step = 310
order by member_id asc, created_time asc) t1,
(select @rownum := 0, @member_id := null, @rank := 0) t0
运行结果:
[email protected],相当于将Oracle中的分析函数是效果一样的,相当于细分来执行每一步动作,个人感觉这里和Oracle中lag()函数原理很像。
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/4899.html