我有一个问题:
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”这一行,因为他获得了最高的“选票”。
如何更改查询以执行此操作?
提前感谢您的帮助:)
答案 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)