2012-09-13 146 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子句中的子查詢,並加入對分組統計信息表。希望這可以幫助。