3

我有一个用户表,其中包含他们投票支持的 aa 用户 id,如下所示:

uid | voted_for
 1  |   3
 2  |   3
 3  |   1

我的目标是根据有多少人投票支持该 uid 来订购 uid。但我不知道该怎么做。

所以最终的结果是:

uid | Total_Votes
 3  |     2
 1  |     1
 2  |     0

希望您能帮助解释为此构建 SQL 的最佳方法。

4

2 回答 2

2

也许这样的事情将有助于自己加入表格:

SELECT u.*, voted_for_cnt
FROM users u
   LEFT JOIN (
      SELECT voted_for, count(1) voted_for_cnt 
      FROM users
      GROUP BY voted_for
   ) t ON u.uid = t.voted_for
ORDER BY t.voted_for_cnt DESC
于 2013-05-28T00:50:27.517 回答
1

这个简单的查询将产生您请求的输出:

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零分。

或者,您可以只选择您想要的那些列:

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
于 2013-05-28T04:36:59.400 回答