Mysql 先筛选,后安分组取最大值的优化

时间:2023-01-03 15:07:26
需求是这样的:
要取出这段时间(logtime)内,用户(username)首次登陆的IP(logip)。
注:1.表中登陆一次就会对应一条记录
2.表中字段很多,

因为还需要余其他表去关联,现在效率很低,急需优化。
下面是我目前的处理方式:
先查询出这段时间内所有的登陆记录
SELECT a.username,a.logip,a.logtime  from
member.loginlog a
where 
a.logClient='WX_GAME'
and a.logtime>='2013-10-12'
and a.logtime<'2013-10-30'
Mysql 先筛选,后安分组取最大值的优化
然后把这些数据作为虚拟表,按照username分组取ip、
SELECT a.* from (SELECT a.username,a.logip,a.logtime  from
member.loginlog a
where 
a.logClient='WX_GAME'
and a.logtime>='2013-10-12'
and a.logtime<'2013-10-30') a,(SELECT b.username,min(b.logtime) logtime from (SELECT a.username,a.logip,a.logtime  from
member.loginlog a
where 
a.logClient='WX_GAME'
and a.logtime>='2013-10-12'
and a.logtime<'2013-10-30') b GROUP BY b.username) b where a.username=b.username 
and a.logtime=b.logtime 
可以实现目的,但这只是这个查询的一部分,整个查询耗时严重,
求大牛给个高效的办法。

3 个解决方案

#1


举例说明
select * from tt a where a.logtime>='2013-10-12'
 and a.logtime<'2013-10-30'
and not exists(select 1 from tt where a.username=username
and a.logtime>logtime)

#2


时间上加索引
select *
from loginlog a
where logClient='WX_GAME' and a.logtime>='2013-10-12'
and a.logtime<'2013-10-30'
and not exists (select 1 from loginlog where A.username=username and A.logtime<logtime and logClient='WX_GAME' and a.logtime>='2013-10-12'
and a.logtime<'2013-10-30')

#3


参考下贴中的多种方法

http://blog.csdn.net/acmain_chm/article/details/4126306
[征集]分组取最大N条记录方法征集,及散分....

#1


举例说明
select * from tt a where a.logtime>='2013-10-12'
 and a.logtime<'2013-10-30'
and not exists(select 1 from tt where a.username=username
and a.logtime>logtime)

#2


时间上加索引
select *
from loginlog a
where logClient='WX_GAME' and a.logtime>='2013-10-12'
and a.logtime<'2013-10-30'
and not exists (select 1 from loginlog where A.username=username and A.logtime<logtime and logClient='WX_GAME' and a.logtime>='2013-10-12'
and a.logtime<'2013-10-30')

#3


参考下贴中的多种方法

http://blog.csdn.net/acmain_chm/article/details/4126306
[征集]分组取最大N条记录方法征集,及散分....