我有一个查询,它返回退休次数最多的跑步者:
SELECT runnerName, COUNT(runner) Retired
FROM `lapInfo` A JOIN `runner` B
ON A.lapInfoRunnerNo = B.runnerNo
WHERE `lapInfoRetired`=1
GROUP BY runnerName
ORDER BY COUNT(lapInfoRunnerNo) DESC
LIMIT 1;
目前,如果两名选手都退役一次并且没有其他选手退役,我希望查询返回这两名选手,因为他们都退役了最多次。我尝试过MAX()而不是LIMIT,但它仍然只返回一个值。
我正在使用MySQL。
由于
答案 0 :(得分:1)
您可以在子查询中获取最大退休计数,然后将其进行比较以获得具有最大退休计数的所有参与者
SELECT runnerName, runnerno
from runner r
join lapinfo l
on r.runnerno = l.lapinfoRunnerNo
group by runnerName
having sum(lapinfoRetired=1) =(
SELECT SUM(lapInfoRetired=1) as TotalRetired
FROM lapInfo
GROUP BY lapInfoRunnerNo
ORDER BY SUM(lapInfoRetired=1) desc
LIMIT 1 )
答案 1 :(得分:0)
如果您不介意将这些名称作为逗号分隔列表,您可以这样做:
SELECT GROUP_CONCAT(runnerName), Retired
FROM (SELECT runnerName, COUNT(runner) as Retired
FROM `lapInfo` A JOIN
`runner` B
ON A.lapInfoRunnerNo = B.runnerNo
WHERE `lapInfoRetired`=1
GROUP BY runnerName
) r
GROUP BY Retired
ORDER BY Retired DESC
LIMIT 1;
顺便说一句,使用表别名是个好主意。但是当它们是表名的缩写时更好。我建议li
为lapinfo
,r
为runner
。