目前,我正在使用名爲league_standing
的表格實現以下結果,並在每次比賽結束後進行更新。我希望能夠處理表matches
中的一個查詢。如何通過兩列中的外鍵來總結列?
Teams
打對方兩次,均是主場還是客場。請注意如何team_id
是在兩列home_team_id
和away_team_id
+----------------------------------+
| Matches |
+----------------------------------+
| id |
| league_id (FK League) |
| season_id (FK Season) |
| home_team_id (FK Team) |
| away_team_id (FK Team) |
| home_score |
| away_score |
| confirmed |
+----------------------------------+
這是我曾嘗試但失敗:
select team.name, HomePoints + AwayPoints points
from team join (
select team.id,
sum(case when home.home_score > home.away_score then 3
when home.home_score = home.away_score then 1 else 0 end) HomePoints,
sum(case when away.away_score > away.home_score then 3 else 0 end) AwayPoints
from team
join matches home on team.id = home.home_team_id
join matches away on team.id = away.away_team_id
WHERE home.league_id = 94
AND home.season_id = 82
AND home.confirmed IS NOT NULL
group by id
) temp on team.id = temp.id
order by points desc;
它讓我有錯誤之分:
而這一次只給我主場聯賽的正確結果
SELECT * FROM
(
SELECT team.name, home_team_id AS team_id,
COUNT(*) AS played,
SUM((CASE WHEN home_score > away_score THEN 1 ELSE 0 END)) AS won,
SUM((CASE WHEN away_score > home_score THEN 1 ELSE 0 END)) AS lost,
SUM((CASE WHEN home_score = away_score THEN 1 ELSE 0 END)) AS drawn,
SUM(home_score) AS goalsFor,
SUM(away_score) AS goalsAgainst,
SUM(home_score - away_score) AS goalDifference,
SUM((CASE WHEN home_score > away_score THEN 3 WHEN home_score = away_score THEN 1 ELSE 0 END)) AS points
FROM matches
INNER JOIN team ON matches.home_team_id = team.id
WHERE league_id = 94
AND season_id = 82
AND confirmed IS NOT NULL
GROUP BY home_team_id
UNION
SELECT team.name, away_team_id AS team_id,
COUNT(*) AS played,
SUM((CASE WHEN away_score > home_score THEN 1 ELSE 0 END)) AS won,
SUM((CASE WHEN home_score > away_score THEN 1 ELSE 0 END)) AS lost,
SUM((CASE WHEN home_score = away_score THEN 1 ELSE 0 END)) as drawn,
SUM(away_score) AS goalsFor,
SUM(home_score) AS goalsAgainst,
SUM(away_score - home_score) AS goalDifference,
SUM((CASE WHEN away_score > home_score THEN 3 WHEN away_score = home_score THEN 1 ELSE 0 END)) AS points
FROM matches
INNER JOIN team ON matches.away_team_id = team.id
WHERE league_id = 94
AND season_id = 82
AND confirmed IS NOT NULL
GROUP BY away_team_id
) x
GROUP BY team_id
ORDER BY points DESC;
如果有幫助,我的數據庫模式:
我卡住了!希望你能幫助。
不要這樣做。數據庫規範化的一個規則是不存儲計算值。您可以通過在其他表格上運行選擇查詢來始終顯示積分榜。 –
@DanBracuk因此,對匹配運行選擇查詢並使用PHP計算排名會更好嗎? – Jonathan