2011-03-17 197 views
0

我有是非常緩慢運行查詢:MySQL的子查詢優化

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

我試圖把它改寫爲左加入,但它返回0結果:

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 

莫非有人指出我的錯誤在這裏?

+0

嘗試使用#FULL OUTER JOIN因爲它會指向你所有的東西,而不匹配的東西將返回爲空。 – B4NZ41 2011-03-17 19:59:12

回答

3
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 

你需要對指標

  • (games.id,平臺名稱)
  • (collections.user_id,collections.game_id)
+1

我認爲最好的索引是'遊戲(id)'和'集合(user_id,game_id)'select *讓其餘部分沒有意義。請考慮將'select *'更改爲'select games。*' – RichardTheKiwi 2011-03-17 20:04:16

+0

謝謝,我更新了查詢順序。 – Pentium10 2011-03-17 20:07:59

+0

你們是搖滾明星!謝謝。 – madzilla 2011-03-17 20:12:08