3

次のように投票したユーザー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誰もユーザーに投票しなかった場合、この 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
于 2013-05-28T04:36:59.400 に答える