用于在类SO系统中显示每个用户的总投票数的SQL查询

时间:2011-12-08 20:36:25

标签: sql

考虑类似StackOverflow的系统的简化表模式:

表格
用户(身份证,姓名)
问题(id,user_id,question)
投票(id,question_id)

我将如何编写

的SQL查询
  • 列出每个用户以及所有问题的总票数,按大多数投票排序?
  • 给定user_id,返回单个用户记录及其总票数?

用户名|总票数(desc)

3 个答案:

答案 0 :(得分:1)

关于你的第一个问题:

SELECT u.name, COUNT(v.id) AS TotalVotes
    FROM User u
        LEFT JOIN Question q
            INNER JOIN Vote v
                ON q.id = v.question_id
            ON u.id = q.user_id
    GROUP BY u.name
    ORDER BY TotalVotes DESC

关于你的第二个问题:

SELECT u.name, COUNT(v.id) AS TotalVotes
    FROM User u
        LEFT JOIN Question q
            INNER JOIN Vote v
                ON q.id = v.question_id
            ON u.id = q.user_id
    WHERE u.id = @GivenUserId
    GROUP BY u.name

答案 1 :(得分:1)

select User.id,
User.name,
count(vote.id) as Votes
from User 
left join Question
on User.id = Question.user_id
left join Vote
on Vote.question_id = Question.id
group by user.id, User.name
order by 3 desc

答案 2 :(得分:0)

    SELECT user.name, question.question, count(vote.id) votes
    FROM user
    inner join question on user.id=question.user_id
    inner join vote on question.id=vote.question_id
    GROUP BY user.name, question.question
    ORDER BY votes