Mohammad Masoudian
Mohammad Masoudian

Reputation: 3491

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 enter image description here

Upvotes: 0

Views: 64

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86764

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.

Upvotes: 1

Related Questions