2016-10-04 43 views
-2

我的SQL查詢需要很多時間來執行,因爲事務表非常巨大。我正在尋找方法來改善此查詢的性能。如何使用JOINS和嵌套SELECT來優化此SQL查詢?

SELECT users.user_id, users.name as user, IFNULL(SUM(IF(transactions.recipient_account = users.account_id,transactions.money,0-transactions.money)),0) as total 
FROM users as users 
JOIN 
(SELECT account_id as system_account FROM accounts WHERE user_guid IS NULL AND name IS NULL LIMIT 1) as tmp 
LEFT JOIN (transactions as transactions) 
    ON (users.account_id IN (transactions.sender_account,transactions.recipient_account)) 
WHERE (users.hidden = 0) 
    AND ((transactions.flags & 1) = 0 
    OR transactions.flags IS NULL) 
GROUP BY users.user_guid 
ORDER BY total DESC 
LIMIT 0,5 

我對索引很感興趣,但我不確定如何在這裏使用它們。

謝謝任何​​幫助或建議。

+0

請向我們提供解釋結果,並向我們提供您在受影響的表格和索引中包含的字段的索引。沒有這些,任何答案都將基於純粹的猜測。 – Shadow

+1

通常,您將爲查詢的where子句中使用的列添加索引。您可以在這些列上添加/刪除索引,以查看它是否可以提高性能。 – Clay

回答

-1
accounts: INDEX(user_guid, name, account_id) 
users: INDEX(hidden, account_id) 

請爲每個表提供SHOW CREATE TABLE;與此同時,我們可能會有進一步的建議。

Index Cookbook