我有1个包含所有信息的主表和1个结构几乎相同但值略有不同的表。现在,我想比较这些值并获得最高的差额。我在每个查询(a1-a5)的查询中都使用了此功能,并且在每个查询的循环中我再次查询并使用结果进行一些计算...我不知道,这很杂乱,我不确定如何获得此结果以一种干净的方式。
这是2个表的结构:
+----------+----------+--------+-----+-----+-----+-----+-----+--------------+
| HomeTeam | AwayTeam | Result | a1 | a2 | a3 | a4 | a5 | Date |
+----------+----------+--------+-----+-----+-----+-----+-----+--------------+
| team1 | team2 | H | 5 | 2 | 4 | 4 | 3 | 11-04-2017 |
| team3 | team4 | A | 6 | 8 | 4 | 2 | 6 | 11-04-2017 |
| team1 | team3 | D | 3 | 7 | 9 | 7 | 2 | 12-04-2017 |
| team4 | team2 | H | 2 | 4 | 8 | 6 | 5 | 12-04-2017 |
+----------+----------+--------+-----+-----+-----+-----+-----+--------------+
+----------+----------+-----+-----+-----+-----+-----+
| HomeTeam | AwayTeam | a1 | a2 | a3 | a4 | a5 |
+----------+----------+-----+-----+-----+-----+-----+
| team1 | team2 | 2 | 3 | 5 | 3 | 3 |
| team3 | team4 | 5 | 7 | 5 | 2 | 3 |
| team1 | team3 | 4 | 2 | 8 | 6 | 5 |
| team4 | team2 | 2 | 5 | 5 | 6 | 4 |
+----------+----------+-----+-----+-----+-----+-----+
这就是我要打印的内容:
team 1 vs team 2 biggest increase was 150% (a1 -> 5 vs 2) on 11-04-2017
team 3 vs team 4 biggest increase was 100% (a5 -> 6 vs 3) on 11-04-2017
team 1 vs team 3 biggest increase was 250% (a2 -> 7 vs 2) on 12-04-2017
team 4 vs team 2 biggest increase was 60% (a3 -> 8 vs 5) on 12-04-2017
当我输入此内容时,我想也许只使用一个查询即可从两个表中获取所有内容,并使用值进行一些计算?不确定。有人可以在正确的方向上给我很大的帮助吗?
答案 0 :(得分:0)
我们可以在此处使用GREATEST
来查找每次比赛的最大点差:
SELECT
HomeTeam,
AwayTeam,
GREATEST(t1.a1 - t2.a1, t1.a2 - t2.a2, t1.a3 - t2.a3, t1.a4 - t2.a4, t1.a5 - t2.a5) AS max_diff
FROM table1 t1
INNER JOIN table2 t2
ON t1.HomeTeam = t2.HomeTeam AND t1.AwayTeam = t2.AwayTeam;
如果您还想要实际的a
值,那么将需要做更多的工作,尤其是在您的数据未标准化的情况下。您可能希望对数据进行标准化处理,以解决除上述之外的任何复杂工作。