在mysql中找到多个分组的第二高值

时间:2019-10-22 19:09:23

标签: mysql sql

我目前正在mysql中选择一个选举数据库,正在寻找有关查询的帮助。照原样,我现在可以使用查询找到所有选举的获胜者:

SELECT DISTINCT c.Office, c.Election, c.fName, c.mName, c.lName, MAX(v.votes) as Votes
-> FROM candidates as c, (SELECT DISTINCT c_id, COUNT(c_id) as votes FROM votes
-> GROUP BY c_id) as v
-> WHERE c.c_id = v.c_id
-> GROUP BY Office, Election;

现在,我正在寻找每次选举的亚军。我尝试了以下查询:

SELECT DISTINCT c.Office, c.Election, c.fName, c.mName, c.lName, MAX(v.votes) as Votes
-> FROM candidates as c, (SELECT DISTINCT c_id, COUNT(c_id) as votes FROM votes
-> GROUP BY c_id) as v, (SELECT DISTINCT c_id, COUNT(c_id) as votes FROM votes
-> GROUP BY c_id) as v2
-> WHERE c.c_id = v.c_id
-> AND v.votes < v2.votes
-> GROUP BY Office, Election;

哪些人成功地使第一次选举获得亚军,但随后的所有选举又获得了胜利者。如何改善查询,使其将亚军条件应用于集合中的所有选举?

编辑:这是针对mysql 5.1

1 个答案:

答案 0 :(得分:0)

我想您缺少投票表之间的连接条件。尝试以下-

SELECT DISTINCT c.Office
               ,c.Election
               ,c.fName
               ,c.mName
               ,c.lName
               ,MAX(v.votes) as Votes
FROM candidates as c
JOIN (SELECT c_id
            ,COUNT(c_id) as votes
      FROM votes
      GROUP BY c_id) as v ON c.c_id = v.c_id
JOIN (SELECT c_id
            ,COUNT(c_id) as votes
      FROM votes
      GROUP BY c_id) as v2 ON v.c_id = v2.c_id
                          AND v.votes < v2.votes
GROUP BY c.Office
        ,c.Election
        ,c.fName
        ,c.mName
        ,c.lName

此外,我已经将您的旧联接语法转换为新的ANSI样式的联接,这更易于阅读。