简体   繁体   中英

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?

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)

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