我正在整理一个新项目,我需要做的一件事情就是得到假足球(美国)比赛的结果。我在php和mysql中使用CodeIgniter作为我的框架。我的dbfiddle如下:
https://www.db-fiddle.com/f/5Q7QezddpNEGabaia2w5FQ/0
现在,如您所见,每个团队都有一个home_team_id和away_team_id条目。我想做的是查询每个队只得到一个结果(无论他们是在家还是不在)。如果不需要,我宁愿不以编程方式处理此数据。
结果应类似于以下内容:
SELECT week, home_team_id, away_team_id,
my_score, their_score,
a.team_name as home_team, b.team_name as away_team
FROM nfl_user_matchups nm
LEFT JOIN user_teams a ON nm.home_team_id = a.user_teams_id
LEFT JOIN user_teams b ON nm.away_team_id = b.user_teams_id
WHERE week = 1
预期的最终数据将是这样(my_score将是home_team_id得分,而他们的得分将是away_team_id得分):
+------+--------------+--------------+----------+-------------+
| week | home_team_id | away_team_id | my_score | their_score |
+------+--------------+--------------+----------+-------------+
| 1 | 3 | 9 | 112 | 144 |
+------+--------------+--------------+----------+-------------+
| 1 | 7 | 2 | 85 | 96 |
+------+--------------+--------------+----------+-------------+
| 1 | 1 | 6 | 111 | 114 |
+------+--------------+--------------+----------+-------------+
| 1 | 4 | 5 | 99 | 125 |
+------+--------------+--------------+----------+-------------+
| 1 | 8 | 10 | 140 | 122 |
+------+--------------+--------------+----------+-------------+
答案 0 :(得分:1)
您的问题陈述基本上意味着一对竞争的团队,即(1,2)
,应与(2,1)
相同。处理此类要求的一种方法是确保对于这两个团队之间的任何比赛,我们确保它们的顺序相同。因此,基本上,我们从两个团队中获得Least()
团队ID值,并始终将其放在第一个索引中;并且Greatest()
的值始终位于第二(最后)索引处。值得注意的是,Greatest()
与Max()
不同。 Max()
函数可计算一列的最大值;而Greatest()
通常用于比较行中的值。
现在,我们可以简单地在这对上GROUP BY
并根据需要计算聚合。在确定家庭/离家分数时,您将需要使用CASE .. WHEN
表达式来确定特定行的家庭ID最少,还是离家ID:
SELECT
week,
LEAST(home_team_id, away_team_id) AS home_id,
GREATEST(home_team_id, away_team_id) AS away_id,
MAX(CASE
WHEN LEAST(home_team_id, away_team_id) = home_team_id
THEN my_score
ELSE their_score
END) AS home_score,
MAX(CASE
WHEN GREATEST(home_team_id, away_team_id) = away_team_id
THEN their_score
ELSE my_score
END) AS away_score
FROM nfl_user_matchups
WHERE week = 1
GROUP BY
week,
home_id,
away_id;