2012-09-13 102 views
0

我有下面的SQL代码,这是从MySQL数据库。现在它给了我期望的结果,但是查询速度很慢,我想我应该在继续之前加快查询速度。SQL查询/慢

表agentstatusinformation有:

PKEY(主键),用户ID(整数),agentstate(整数)

表axpuser包含了用户的姓名:

PKEY(主键)< - 这是我相信这可以改进对用户ID的关键,登录ID(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) 

,但我看不到T的木材他树。

非常感谢。

+1

究竟什么是你想从这个查询来获取? apxuser中列出的所有用户的状态? –

+0

编辑用'EXPLAIN' – Kermit

+0

你的问题可以在agentstatusinformation有很多axpuser,还是一个? –

回答

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索引(用户ID,p键)。

嵌套查询不应该造成一个问题,只要有上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) 
      ) 
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) 
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子句中的子查询,并加入对分组统计信息表。希望这可以帮助。