2015-07-01 159 views
0

我有3個表:結合3 SQL SELECT到一個語句

  • 隊(id_team,名稱,id_season)
  • 四季(id_season,名稱,nbr_teams)
  • Teams_Stats(id_stats,id_game,id_team ,勝利,失敗,平局)

我有3個查詢正在工作的單獨精確:

SELECT T.name, count(TS.victory) as Wins 
FROM Teams T 
JOIN Seasons S ON T.id_season = S.id_season AND S.name = '2015' 
LEFT JOIN Teams_Stats TS ON TS.id_team = T.id_team AND TS.victory = 1 
GROUP BY T.name 
ORDER BY T.name 

SELECT T.name, count(TS.defeat) as Losses 
FROM Teams T 
JOIN Seasons S ON T.id_season = S.id_season AND S.name = '2015' 
LEFT JOIN Teams_Stats TS ON TS.id_team = T.id_team AND TS.defeat = 1 
GROUP BY T.name 
ORDER BY T.name 

SELECT T.name, count(TS.victory) as Draws 
FROM Teams T 
JOIN Seasons S ON T.id_season = S.id_season AND S.name = '2015' 
LEFT JOIN Teams_Stats TS ON TS.id_team = T.id_team AND TS.draw = 1 
GROUP BY T.name 
ORDER BY T.name 

我想知道如何才能得到相同的結果,但只有1個查詢。我無法得到它?也許有人可以拋出一些光...

我明白,

謝謝。

回答

1

可以使用條件彙總:

SELECT T.name, 
     sum(TS.victory=1) as Wins, 
     sum(TS.defeat=1) as Losses, 
     sum(TS.draw =1) as Draws 
FROM Teams T 
JOIN Seasons S ON T.id_season = S.id_season AND S.name = '2015' 
LEFT JOIN Teams_Stats TS ON TS.id_team = T.id_team 
GROUP BY T.name 
ORDER BY T.name 

Demo here

+0

感謝您的鏈接,我不知道那種測試的是網上已有的。你真的幫助我。感謝您的回答,相當整潔! :) – Vini