请查看图片 ERROR SCREENSHOT
表格:候选人
+-----+---------+
| id | Name |
+-----+---------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
+-----+---------+
表格:投票
+-----+--------------+
| id | CandidateId |
+-----+--------------+
| 1 | 2 |
| 2 | 4 |
| 3 | 3 |
| 4 | 2 |
| 5 | 5 |
+-----+--------------+
id is the auto-increment primary key, CandidateId is the id appeared in Candidate table.
编写一个sql来查找获胜者的姓名,上面的示例将返回获胜者B。
+------+
| Name |
+------+
| B |
+------+
注意: 您可能会假设没有平局,换句话说,最多将有一名获胜者。
为什么此代码无法正常工作?尝试无限使用
SELECT c.Name AS Name
FROM Candidate AS c
JOIN
(SELECT r.CandidateId AS can, MAX(r.Total_vote) AS big
FROM (SELECT CandidateId, COUNT(id) AS Total_vote
FROM Vote
GROUP BY CandidateId) AS r) AS v
ON c.id = v.can;
答案 0 :(得分:0)
在您的查询中,这里:Single<String>
您使用SELECT r.CandidateId AS can, MAX(r.Total_vote) AS big
聚合函数,而没有MAX
,这是不正确的SQL。
尝试:
group by
答案 1 :(得分:0)
这是一个join
/ group by
查询,带有order by
:
select c.name
from candidate c join
vote v
on v.candidateid = c.id
group by c.id, c.name
order by count(*) desc
limit 1;
答案 2 :(得分:0)
SELECT c.Name AS Name
FROM Candidate AS c JOIN (SELECT r.CandidateId AS can
FROM
(SELECT CandidateId, COUNT(id) AS Total_vote
FROM Vote
GROUP BY CandidateId) AS r
WHERE r.Total_vote = (SELECT MAX(r.Total_vote) FROM (SELECT
CandidateId, COUNT(id) AS Total_vote
FROM Vote
GROUP BY CandidateId) r)) AS v
ON c.id = v.can;
这是更新的代码
我的代码有两个错误。第一个是“如果选择列表中有任何未聚合的列,则使用像Max这样的聚合需要使用Group By子句”,但是不确定为什么我的先前代码仍然可以运行并且没有显示错误。也许系统在运行时自动按功能添加分组。
第二个是max不能与这种格式的Group by一起使用。