首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL查询/慢速

问SQL查询/慢速
EN

Stack Overflow用户
提问于 2012-09-13 22:55:46
回答 3查看 226关注 0票数 0

我有下面的SQL代码,这是从一个MySQL数据库。现在,它给出了我期望的结果,但是查询速度很慢,我认为在进一步执行之前,我应该加快查询速度。

表agentstatusinformation包含:

PKEY (主键),userid (整数),agentstate (整数)

表axpuser包含用户名:

PKEY (主键) <--这是userid,loginid (usersname)的键

代码语言:javascript
复制
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)

我相信这是可以改进的,但我不能本末倒置。

非常感谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-13 23:46:23

查询的问题在于嵌套的selects。特别是,In子句中的子查询在MySQL中是有问题的。它被where子句过滤的每一行调用。

以下操作可以修复此问题:

代码语言:javascript
复制
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子句中会更好:

代码语言:javascript
复制
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)
             )
票数 1
EN

Stack Overflow用户

发布于 2012-09-13 23:08:29

我不确定这是不是你想要的,但我认为差不多了:

代码语言:javascript
复制
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子句中的子选择,并针对分组的统计信息表进行联接。希望这能有所帮助。

票数 2
EN

Stack Overflow用户

发布于 2012-09-13 23:05:09

代码语言:javascript
复制
 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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12409132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档