简体   繁体   中英

Executing extremely slow MySQL query

this query has multiple JOIN including aggregate functions

executing this query for approximately 6000 users took 20 seconds.

is there any other method to run this query faster?

SELECT users.id, SUM(orders.totalCost) AS bought, COUNT(comment.id) AS commentsCount, COUNT(topics.id) AS topicsCount, COUNT(users_login.id) AS loginCount, COUNT(users_download.id) AS downloadsCount 
FROM users 
LEFT JOIN orders ON users.id=orders.userID AND orders.status=1 
LEFT JOIN comment ON users.id=comment.userID 
LEFT JOIN topics ON users.id=topics.userID 
LEFT JOIN users_login ON users.id=users_login.userID 
LEFT JOIN users_download ON users.id=users_download.userID 
WHERE users.id='$userID'
GROUP BY users.id 
ORDER BY `bought` DESC

The result of running explain 在此处输入图片说明

The EXPLAIN output shows you are doing full-table scans on everything except users . You need to create secondary (non-unique) indexes on userID on all the other tables in the join. That will speed up queries on individual users.

However, if you're going to process all users in one pass then do a single select without a WHERE users.id= clause. Your aggregation returns only one row per user and you should create a single resultset containing all the rows and iterate over that, instead of reissuing the query once per user. In this case the secondary indexes may still help as counts can be determined from the index alone without looking at the tables themselves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM