我有下面的SQL代码,这是从一个MySQL数据库。现在,它给出了我期望的结果,但是查询速度很慢,我认为在进一步执行之前,我应该加快查询速度。
表agentstatusinformation包含:
PKEY (主键),userid (整数),agentstate (整数)
表axpuser包含用户名:
PKEY (主键) <--这是userid,loginid (usersname)的键
select distinct (select loginid from axpuser where axpuser.pkey = age.userid),
case
when agentstate = 1 then 'Ready'
when agentstate = 3 then 'Pause'
end as state
from agentstatusinformation age
where (userid, pkey) in
(select userid, max(pkey) from agentstatusinformation group by userid)我相信这是可以改进的,但我不能本末倒置。
非常感谢。
发布于 2012-09-13 23:46:23
查询的问题在于嵌套的selects。特别是,In子句中的子查询在MySQL中是有问题的。它被where子句过滤的每一行调用。
以下操作可以修复此问题:
select distinct (select loginid from axpuser where axpuser.pkey = age.userid),
case
when agentstate = 1 then 'Ready'
when agentstate = 3 then 'Pause'
end as state
from agentstatusinformation age
where exists (select userid, max(pkey)
from agentstatusinformation a2
where a2.userid = age.userid
group by userid
having age.pkey = max(pkey))您可以通过在agenstatusinfromation(userid,pkey)上创建索引来使其运行得更快。
只要axpuser.pkey上有索引,嵌套的select就不会造成问题。但是,我认为将其作为连接放在FROM子句中会更好:
select distinct axpuser.loginid,
case
when agentstate = 1 then 'Ready'
when agentstate = 3 then 'Pause'
end as state
from agentstatusinformation age left outer join
axpuser
on axpuser.key = age.userid
where exists (select userid, max(pkey)
from agentstatusinformation a2
where a2.userid = age.userid
group by userid
having age.pkey = max(pkey)
)发布于 2012-09-13 23:08:29
我不确定这是不是你想要的,但我认为差不多了:
Select loginid, case when c.agentstate=1 Then 'Ready'
when c.agentstate=3 then 'Pause'
end state
from axpuser a
join (select userid, max(pkey) pkey
from agentstatusinformation
group by userid ) b
on a.userid=b.userid
join agentstatusinformation c
and b.pkey=c.pkey这消除了初始SELECT子句中的子选择,并针对分组的统计信息表进行联接。希望这能有所帮助。
发布于 2012-09-13 23:05:09
select ax.loginid,
case
when age.agentstate = 1 then 'Ready'
when age.agentstate = 3 then 'Pause'
end as state
from
agentstatusinformation age
join
axpuser ax
on age.userid = ax.userid and age.pkey=(select max(pkey) from agentstatusinformation group by userid)https://stackoverflow.com/questions/12409132
复制相似问题