2017-08-30 71 views
0

我有一個查詢如何優化具有左硬連接的查詢?

SELECT 
"athlete"."id" AS "athlete_id" 
FROM "athlete" 
LEFT JOIN "athlete_in_game" ON athlete.id = athlete_in_game.id_athlete 
LEFT JOIN "athlete_in_team" ON athlete.id = athlete_in_team.id_athlete 
LEFT JOIN "game" ON 
    athlete_in_team.id_team = game.id_team_home OR 
    athlete_in_team.id_team = game.id_team_away OR 
    athlete_in_game.id_game = game.id 
LEFT JOIN "sport_competition" ON sport_competition.id_game = game.id 
GROUP BY "athlete"."id" 

我需要選擇其在比賽中發揮所有的運動員。但可能是因爲幾場比賽沒有數據在表格「運動員在線遊戲」中,並且在這種情況下,我會從表「athlete_in_team」中的所有運動員參加這些遊戲。正因爲如此,我在第三個左連接中使用雙「OR」。我需要所有書面條件,但由於雙「或」,它可能會工作太久。無論如何,是否有機會優化它?

+0

http://wiki.postgresql.org/wiki/SlowQueryQuestions –

回答

0

我認爲首先你必須首先改善模式。團隊相關信息應該是單獨的表格。和遊戲應該是分開的。你不需要和我想的game表左邊加入。只有加入athlete_in_gameathlete_in_team就足夠了。像這樣

SELECT 
"athlete"."id" AS "athlete_id" 
FROM "athlete" 
LEFT JOIN "athlete_in_game" ON athlete.id = athlete_in_game.id_athlete 
LEFT JOIN "athlete_in_team" ON athlete.id = athlete_in_team.id_athlete 
JOIN "game" ON 
    athlete_in_team.id_team = game.id_team_home OR 
    athlete_in_team.id_team = game.id_team_away OR 
    athlete_in_game.id_game = game.id 
LEFT JOIN "sport_competition" ON sport_competition.id_game = game.id 
GROUP BY "athlete"."id"