要取出这段时间(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'
然后把这些数据作为虚拟表,按照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)
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')
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')
#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)
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')
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')