在体育表中一起加入主场和客场比赛结果

时间:2015-12-12 22:22:22

标签: mysql sql subquery

我在单独的查询中有主页和客场结果的代码,但我不确定如何将它们连接起来以便同时回家。

CODE HOME体育联盟

SELECT
teamName AS Team, 
 Sum(P) AS P,
Sum(W) AS W,
Sum(D) AS D,
 Sum(L) AS L,
SUM(F) as F,
SUM(A) AS A,
SUM(GD) AS GD,
SUM(Pts) AS Pts
  FROM(
  SELECT
  teamHomeID Team,
  1 P,
  IF(matchScoreHome > matchScoreAway,1,0) W,
  IF(matchScoreHome = matchScoreAway,1,0) D,
  IF(matchScoreHome < matchScoreAway,1,0) L,
  matchScoreHome F,
  matchScoreAway A,
  matchScoreHome-matchScoreAway GD,
  CASE WHEN matchScoreHome > matchScoreAway THEN 3 WHEN matchScoreHome =    matchScoreAway THEN 1 ELSE 0 END PTS
 FROM tblmatches WHERE matchstatus = 'FT' AND competitionID = 1 AND seasonID = 2     
) as tot
 JOIN tblteam t ON tot.team=t.teamID
 GROUP BY Team
 ORDER BY SUM(Pts) DESC ;

CODE AWAY体育联盟

 SELECT
 teamName AS Team, 
 Sum(P) AS P,
 Sum(W) AS W,
 Sum(D) AS D,
 Sum(L) AS L,
 SUM(F) as F,
 SUM(A) AS A,
 SUM(GD) AS GD,
 SUM(Pts) AS Pts
 FROM(
 SELECT
 teamAwayID Team,
  1 P,
  IF(matchScoreHome < matchScoreAway,1,0) W,
  IF(matchScoreHome= matchScoreAway,1,0) D,
  IF(matchScoreHome > matchScoreAway,1,0) L,
  matchScoreAway F,
  matchScoreHome A,
  matchScoreAway-matchScoreHome GD,
 CASE WHEN matchScoreHome < matchScoreAway THEN 3 WHEN matchScoreHome = matchScoreAway THEN 1 ELSE 0 END PTS
 FROM tblmatches WHERE matchstatus = 'FT' AND competitionID = 1 AND seasonID = 2
) as tot
 JOIN tblteam t ON tot.team=t.teamID
 GROUP BY Team
 ORDER BY SUM(Pts) DESC ;

每个表格如下所示

 --------------------------------------------------
 ¦ Team Name ¦ P ¦ W ¦ D ¦ L ¦ F  ¦ A  ¦ GD ¦ Pts ¦
 ¦ Man City  ¦ 8 ¦ 6 ¦ 0 ¦ 2 ¦ 23 ¦ 10 ¦ 13 ¦ 18  ¦
 ¦ Tottehham ¦ 8 ¦ 4 ¦ 4 ¦ 0 ¦ 14 ¦ 5  ¦ 9  ¦ 16  ¦
 --------------------------------------------------

我想将两个表一起加入以获得如下内容:

     -----------------------------------------------------------------------------
 Team Name ¦ P ¦ W ¦ D ¦ L ¦ F ¦ A ¦ GD ¦ HW ¦ HD ¦ HL ¦ HF ¦ HA ¦ AW ¦ AD ¦ AL ¦ PTS ¦

1 个答案:

答案 0 :(得分:0)

快速解决方法是将'tot'重命名为'tothome'和'totaway',然后您可以或多或少地合并查询。

但是,您必须参考,例如F为totaway.F以获得球队在客场比赛中得分的目标。

你会得到SUM(P)中P的模糊性。在那里你必须使用SUM(tothome.P)+ SUM(totaway.P)来获得P。