この単純なクエリは、要求した出力を生成します。
select voted_for as uid, count(*) as total_votes
from users
group by 1
order by 2 desc
出力内の各ユーザーに関するすべてのデータが必要な場合は、ユーザーをそれ自体に結合します。
select u.*, count(v.uid) as total_votes
from users u
left join users v on v.voted_for = u.uid
group by 1,2,3,4,5 -- put as many numbers here as there are columns in the users table
order by total_votes desc
total_votes
誰もユーザーに投票しなかった場合、この 2 番目のクエリはスコア 0 を返します。
または、必要な列のみを選択することもできます。
select u.uid, u.name, count(v.uid) as total_votes
from users u
left join users v on v.voted_for = u.uid
group by 1,2
order by 3 desc
```
勝者のみを返すには、次のようにします。
select u.uid, u.name, count(*) as total_votes
from users u
left join users v on v.voted_for = u.uid
group by 1,2
having count(*) = (
select max(c) from (
select count(*) as c from users group by voted_for))
order by 3 desc