# Winning Candidate Problem

## Description

LeetCode Problem 574.

Table: Candidate

``````1
2
3
4
5
6
7
8
9
+-----+---------+
| id  | Name    |
+-----+---------+
| 1   | A       |
| 2   | B       |
| 3   | C       |
| 4   | D       |
| 5   | E       |
+-----+---------+
``````

Table: Vote

``````1
2
3
4
5
6
7
8
9
10
11
+-----+--------------+
| 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.
``````

Write a sql to find the name of the winning candidate, the above example will return the winner B.

``````1
2
3
4
5
+------+
| Name |
+------+
| B    |
+------+
``````

Notes: You may assume there is no tie, in other words there will be only one winning candidate.

## MySQL Solution

``````1
2
3
4
5
6
7
8
select name as 'Name'
from Candidate
join (select Candidateid
from Vote
group by Candidateid
order by count(*) desc
limit 1) as winner
where Candidate.id = winner.Candidateid
``````