如何使用连接查询计算此表的获胜者

时间:2014-04-12 13:47:06

标签: mysql oracle

candidate table  
---------------------------                                

Id    Name
1     James
2     peter
3     robin
4     max

vote table
-----------------------

vote   candidate id   

1       1
1       1
1       1
1       2
1       3
1       3
1       2

如何通过此数据库计算mysql中的获胜者

2 个答案:

答案 0 :(得分:0)

select 
c.name,
sum(v.vote) as total_votes
from candidate c
inner join vote v on v.candidate_id = c.Id
group by c.Id
order by total_votes desc limit 1

这将给予胜利者。

如果您想按顺序列出所有这些,例如从上到下用作

select 
c.name,
sum(v.vote) as total_votes
from candidate c
inner join vote v on v.candidate_id = c.Id
group by c.Id
order by total_votes desc

答案 1 :(得分:0)

假设如果有两个人拥有相同的选票,那么这种情况下会有两个获胜者你可以这样做

SELECT  c.*,
COUNT(*) `votes`,
t.votes_total
FROM candidate c
LEFT JOIN vote v ON(v.candidate_id = c.id)
JOIN (SELECT COUNT(*) votes_total FROM vote 
      GROUP BY candidate_id 
      ORDER BY votes_total DESC
      LIMIT 1) t
GROUP BY  c.id
HAVING votes=t.votes_total
ORDER BY votes DESC

另外,如果你不关心一个获胜者,那么你可以使用 Abhik Chakraborty提供的ORDER BY和LIMIT技术

Fiddle demo