1

我有兩個表:可以在「首選用戶」MySQL查詢中優化左連接嗎?

poll_response(poll_id,option_id,USER_ID) (約50萬行數據,500個獨特的民意調查,1000個獨特的選項,以及25000個獨特的用戶)

preferred_users (USER_ID) (約800行)

我想,以確定誰選擇的每個選項是用戶的百分比「首選用戶」(即那些聲譽很高的人)。其他用戶可以迴應投票;爲了確定響應來自首選用戶,加入對preferred_users表是必需的。

下面是我得到了什麼:

SELECT option_id, count(*) AS all_votes, count(preferred_users.user_id) AS preferred_votes 
FROM response 
LEFT JOIN preferred_users ON response.user_id = preferred_users.user_id 
GROUP BY option_id 

查詢吐出表是這樣的:

| option_id | all_votes | preferred_votes 
| 1   | 500  | 150 
| 2   | 550  | 250 
| 3   | 525  | 300 

然後我可以做數學確定的百分比。

問題是查詢經常超時 - 這意味着完成需要一分多鐘。

有沒有什麼辦法擺脫左連接或以其他方式優化查詢?

+0

你對這些表有什麼索引? – 2012-02-27 20:00:50

+0

BTREE索引每個列在poll_response – jawns317 2012-02-27 20:13:45

回答

1

您是否嘗試將它分成兩個查詢 - 一個用於總數,另一個用於首選用戶?我懷疑是什麼導致它慢慢地運行通過計算非空條目的組中的條目(但你可以通過使用解釋來看你自己)。

換句話說:

select option_id, count(*) from response group by option_id 
select option_id, count(*) from response, preferred_users where response.user_id = preferred_user.id group by option_id 

你甚至可以加入他們的行列:

select * from 
    (select option_id, count(*) as total from response group by option_id 
    left join 
    select option_id, count(*) as preferred from response, preferred_users where response.user_id = preferred_user.id group by option_id 
    using (option_id)) 

(不知道我有沒有語法就在那裏,但你的想法)。

此外,您也有preferred_users.id列上的索引,對吧?以及從一個到另一個的外鍵關係?如果沒有,請先嚐試。

+0

這樣的工作(將很好知道某些...)? – 2012-02-28 01:44:56