SQL查询/慢

时间:2012-09-13 14:55:46

标签: mysql sql query-optimization

我有以下SQL代码,这是来自MySQL数据库。现在它给了我期望的结果,但是查询速度很慢,我认为我应该加快这个查询,然后再继续。

表agentstatus信息包含:

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)

我确信这可以改进,但我看不到树木的木材。

非常感谢。

3 个答案:

答案 0 :(得分:2)

不确定这是你想要的,但我认为它很接近:

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子句中的子选择,并且与分组的统计信息表连接。希望这会有所帮助。

答案 1 :(得分:1)

查询的问题是嵌套选择。特别是,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上有索引,嵌套选择不应该导致问题。但是,我认为将它作为连接放在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)
             )

答案 2 :(得分:0)

 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)