mysql 5.x 到目前为止,我已经返回了每个竞争者(由每个参与者都有各自的薪水组成)和竞争者的总薪水。我要获得包含最高薪水的行。
SELECT StageName, MAX(TotalSalary)
FROM (
SELECT StageName, SUM(DailySalary) AS TotalSalary
FROM CONTENDER, PARTICIPANT
WHERE idContender = Contender
GROUP BY idContender
) AS AllContenders;
这给了我一行最高薪水,但它只是给出了第一行的名称,而不是正确的行,这正是我需要找到的
+-------------+-------------+
| StageName | TotalSalary |
+-------------+-------------+
| Life | 2600 |
| Death | 6000 |
| AC/DC | 16000 |
| Yin | 2700 |
| Yang | 3300 |
| Error Group | 1337 |
+-------------+-------------+
这是我从中间选择语句得到的。
我得到的完整代码是生命和16000, 我应该得到的是acdc和16000
答案 0 :(得分:0)
首先,您要按idContender
进行分组,但选择StageName
,这将为您StageName
的每组随机分配idContender
,而不是用错误(仅限MySql问题)。因此,您需要选择StageName, SUM(DailySalary)
,而不是在子查询中选择idContender, SUM(DailySalary)
。最后,您可以使用CONTENDER
将子查询更改为联合查询,并使用order by
和limit
选择具有最高TotalSalary
的第一条记录:
SELECT t1.*, t2.TotalSalary as MaxSalary
FROM CONTENDER t1 join (
SELECT idContender, SUM(DailySalary) AS TotalSalary
FROM CONTENDER, PARTICIPANT
WHERE idContender = Contender
GROUP BY idContender
) AS t2
on t1.id = t2.idContender
order by MaxSalary desc
limit 1