比较两个表中的多列并显示最大的差异

5cnsuln7  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(364)

我有一个包含所有信息的主表和一个结构几乎相同但值略有不同的表。现在我想比较一下这些值,得到最大的差值。我对每一列(a1-a5)进行了查询,在每个查询的循环中,我再次查询并对结果进行了一些计算……我不知道,这很混乱,我不知道如何以一种干净的方式得到它。
这是两个表的结构:

+----------+----------+--------+-----+-----+-----+-----+-----+--------------+
| 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

当我输入这个的时候,我想也许只使用一个查询就可以从两个表中获取所有内容,并使用这些值进行一些计算?不确定…有人能在正确的方向上给我一个很大的帮助,教我怎么做吗?

zpjtge22

zpjtge221#

我们可以用 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 值,那么就需要做更多的工作,特别是考虑到您的数据不是标准化的。您可能需要对数据进行规范化处理,以处理比上述更复杂的问题。

相关问题