2009-06-04 91 views
2

我有一個查詢:MySQL查詢與連接優化

SELECT a.nick,grp,count(*) FROM help_mails^h JOIN佔一個ON h.helper = a.id WHERE關閉= 1 GROUP BY幫手,GRP,a.nick

是什麼此連接錯誤? 當我做了2個查詢:

SELECT helper,grp,count(*) FROM help_mails h WHERE closed = 1 GROUP BY helper,grp; (...) 這是100倍的速度。

EXPLAIN返回此:

id  select_type  table type possible_keys key  key_len  ref  rows Extra 
1 SIMPLE h ref  closed closed 1 const 1846 Using temporary; Using filesort 
1 SIMPLE a ref  PRIMARY  PRIMARY  4 margonem.h.helper 1 Using where; Using index

accounts.id,help_mails.grp和help_mails.closed了索引。

回答

5

請注意,您的第一個查詢不同於第二個查詢。

如果您有兩個accountNICKCOUNT(*)的這些帳戶將在第一個查詢中合併在一起並在第二個單獨返回。

如果你想單獨COUNT的單獨account的總是被退回,可以將您的查詢組合成一個:

SELECT a.nick, gpr, cnt 
FROM (
     SELECT helper, grp, COUNT(*) AS cnt 
     FROM help_mails h 
     WHERE closed = 1 
     GROUP BY 
       helper, grp 
     ) ho 
JOIN accounts a 
ON  a.id = ho.helper 

或更改GROUP BY條件的第一個查詢:

SELECT a.nick, grp, count(*) 
FROM help_mails h 
JOIN accounts a 
ON  h.helper = a.id 
WHERE closed = 1 
GROUP BY 
     helper, grp, a.id, a.nick 

help_mails (closed, helper, grp)上構建複合索引將對您有所幫助,因爲它將用於GROUP BY

1

看起來有什麼不對,help_mails.helper沒有編入索引。

+0

將索引添加到助手字段不會改善任何事情,我檢查了它。 – Thinker 2009-06-04 12:56:10

+0

這對我沒有任何意義,但沒關係。嘗試關閉和助手上的複合鍵。 – chaos 2009-06-04 12:57:24