2013-09-30 306 views
0

我們的一個網站有一個約60'000條記錄的表格。最近我們注意到頁面超時,只能通過將內存限制設置爲-1來解決。這允許頁面加載,但速度很慢。此外,我不相信這是解決問題的正確方法,顯然這表明事情並不完全正確。MySQL子查詢選擇速度很慢

我到輸出管理的查詢頁面正在運行:我在phpMyAdmin跑到這個查詢

SELECT u.*, 
(SELECT COUNT(*) FROM enquiry e WHERE e.user_id = u.id AND e.deleted = 0 AND e.time_started != 0) AS opened_count, 
(SELECT COUNT(*) FROM enquiry e WHERE e.user_id = u.id AND e.deleted = 0 AND e.confirmed = 1 AND e.time_started != 0) AS confirmed_count, 
(SELECT COUNT(*) FROM enquiry e WHERE e.user_id = u.id AND e.deleted = 0 AND e.call_back = 1 AND e.time_started != 0) AS call_back_count 
FROM user u 
WHERE u.active = 1 AND u.deleted = 0 
ORDER BY u.username 

,並接管30秒返回結果。

我覺得查詢需要以某種方式優化,但我正在努力研究如何。我猜我需要使用某種JOIN?

+3

請提供'EXPLAIN'和'DESCRIBE'結果。 – Kermit

回答

7

您確實正在運行> 180,000個查詢,因爲這3個子查詢中的每一個都將針對用戶表中的每一行運行一次。

您可以嘗試簡化與某些組的標準連接,例如,

SELECT user.*, 
    COUNT(enq.id) AS opened_count 
    SUM(e.confirmed = 1) AS confirmed_count 
    SUM(e.call_back = 1) AS call_back_count 
FROM user 
LEFT JOIN enquiry ON enquiry.user_id = user.id 
WHERE user.active = 1 and user.deleted AND enquiry.deleted = 0 
GROUP BY user.id 
+0

這不需要一個組? – Laurence

+0

Woops,對。謝謝。 –

+0

謝謝馬克。這已經造成了巨大的變化。我需要幫助的一件小事 - 如何將我的WHERE條件集成到COUNT查詢中,即'WHERE enquiry.time_started!= 0' – GSTAR