madzilla
madzilla

Reputation: 352

MySQL sub-query optimization

I've got a query that is running awfully slow:

SELECT * 
FROM games
WHERE games.platform =13
AND games.id NOT 
IN (SELECT game_id
FROM collections
WHERE collections.user_id =1)

I attempted to rewrite it as a left join but it's returned 0 results:

SELECT * 
FROM games 
LEFT JOIN collections ON collections.game_id = games.id 
WHERE collections.game_id IS NULL AND collections.user_id = 1 AND games.platform = 13
ORDER BY games.name ASC

Could someone point out my error here?

Upvotes: 0

Views: 152

Answers (1)

Pentium10
Pentium10

Reputation: 207912

SELECT games.* 
FROM   games 
       LEFT JOIN collections 
         ON collections.user_id = 1 
            AND collections.game_id = games.id 
WHERE  games.platform = 13 
       AND collections.game_id IS NULL 
ORDER  BY games.name ASC 

you need indexes on

  • (games.id,platform,name)
  • (collections.user_id,collections.game_id)

Upvotes: 3

Related Questions