在SQL中,如何获取具有特定列的最大值的行?

时间:2010-01-06 18:57:05

标签: sql mysql

我有一个问题:

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a
WHERE ballot_id = 1
GROUP BY a.member_id

产生类似的东西:

votes  member_id
1      paul
5      mike
3      noynoy
10     andy
2      noel

我希望能够得到“andy”这一行,因为他获得了最高的“选票”。

如何更改查询以执行此操作?

提前感谢您的帮助:)

6 个答案:

答案 0 :(得分:5)

您可以使用ORDER BY然后DESC按降序从最高到最低票数进行排序。然后LIMIT结果只有一行(即最高)。

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a
WHERE ballot_id = 1
GROUP BY a.member_id
ORDER BY votes DESC
LIMIT 1

答案 1 :(得分:2)

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a
WHERE ballot_id = 1
GROUP BY a.member_id
ORDER BY COUNT(*) DESC 
LIMIT 1

答案 2 :(得分:2)

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a 
WHERE ballot_id = 1 
GROUP BY a.member_id
ORDER BY votes DESC
LIMIT 1

答案 3 :(得分:1)

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a 
WHERE ballot_id = 1 
GROUP BY a.member_id
ORDER BY COUNT(*) DESC
LIMIT 1

答案 4 :(得分:1)

如果重复最大值,则使用COUNT()将不会选择所有行。我的建议是使用MAX()

SELECT *
FROM ballots a
WHERE votes = (SELECT max(votes) FROM ballots)

答案 5 :(得分:1)

使用专用view来计算投票

可能更容易获得

CREATE VIEW v_votes AS 
  SELECT member_id, ballot_id,  COUNT(*) AS votes FROM ballots GROUP BY member_id

然后使用 HAVING 子句

SELECT * FROM v_votes HAVING MAX(votes)