我有两个看起来像这样的MySQL表
队
id name abbr_name badge slogan captain
1 TEAM1 TM1 NULL NULL NULL
2 TEAM2 TM2 NULL NULL NULL
3 TAEM3 TM3 NULL NULL NULL
4 TEAM4 TM4 NULL NULL NULL
5 TEAM5 TM5 NULL NULL NULL
....
匹配条目
id season match_day host guest time host_score guest_score forfait mvp
1 1 1 3 4 NULL 10 2 NULL 43
2 1 1 5 6 NULL 2 2 NULL 16
3 1 1 9 10 NULL 6 3 NULL 49
4 1 1 2 1 NULL 5 5 NULL 29
5 1 1 7 8 NULL 4 2 NULL 52
6 1 2 1 4 NULL 7 3 NULL 75
....
我想做的是创建一个查询,它可以为我提供值为
的所有行Team_Id, Team_name, Team_N_Match_Played, Team_N_Match_Won, Team_N_Match_Lost
这是否可以在不使用PHP操纵所有数据并直接使用MySQL查询的情况下实现? 我不知道如何在MySQL中解决这个问题。
答案 0 :(得分:1)
使用MySQL Count。
SELECT
t.Team_Id, t.Team_name,
COUNT(meh.id) + COUNT(meg.id) AS Team_N_Match_Played,
COUNT(meh.host_scrore > meh.guest_score) + COUNT(meg.guest_score > meg.host_scrore ) AS Team_N_Match_Won,
Team_N_Match_Lost
COUNT(meh.host_scrore < meh.guest_score) + COUNT(meg.guest_score < meg.host_scrore )
FROM Teams AS t
JOIN Match_Entries AS meh ON t.id = meh.host
JOIN Match_Entries AS meg ON t.id = meg.guest
答案 1 :(得分:0)
像这样的东西会这样做
SELECT Teams.id, Teams.name, COUNT(a.id) + COUNT(d.id) + COUNT(c.id) + COUNT(f.id) + COUNT(b.id) + COUNT(e.id) AS GamesCnt, COUNT(a.id) + COUNT(d.id) AS GamesWon, COUNT(c.id) + COUNT(f.id) AS GamesLost, COUNT(b.id) + COUNT(e.id) AS GamesDrawn
FROM Teams
LEFT OUTER JOIN MatchEntries a ON Teams.id = a.host AND a.host_score > a.guest_score
LEFT OUTER JOIN MatchEntries b ON Teams.id = b.host AND b.host_score = b.guest_score
LEFT OUTER JOIN MatchEntries c ON Teams.id = c.host AND c.host_score < c.guest_score
LEFT OUTER JOIN MatchEntries d ON Teams.id = d.guest AND d.guest_score > d.host_score
LEFT OUTER JOIN MatchEntries e ON Teams.id = e.guest AND e.guest_score = e.host_score
LEFT OUTER JOIN MatchEntries f ON Teams.id = f.guest AND f.guest_score < f.host_score
GROUP BY Teams.id
答案 2 :(得分:0)
MatchEntries = dc_match 团队= dc_teams
SELECT
team_id,
name,
SUM(P) AS played,
SUM(W) AS won,
SUM(D) AS draw,
SUM(L) AS lost,
SUM(PTS) AS points
FROM(
SELECT
host team_id,
CASE
WHEN host_score IS NULL THEN 0
ELSE 1
END P,
IF (host_score > guest_score,1,0) W,
IF (host_score = guest_score,1,0) D,
IF (host_score < guest_score,1,0) L,
CASE
WHEN host_score > guest_score THEN 3
WHEN host_score = guest_score THEN 1
ELSE 0
END PTS
FROM dc_match
UNION ALL
SELECT
guest team_id,
CASE
WHEN guest_score IS NULL THEN 0
ELSE 1
END P,
IF (guest_score > host_score,1,0) W,
IF (guest_score = host_score,1,0) D,
IF (guest_score < host_score,1,0) L,
CASE
WHEN guest_score > host_score THEN 3
WHEN guest_score = host_score THEN 1
ELSE 0
END PTS
FROM dc_match
) AS RNK
LEFT JOIN dc_team t
ON RNK.team_id = t.id
GROUP by team_id
ORDER BY points DESC