考虑类似StackOverflow的系统的简化表模式:
表格
用户(身份证,姓名)
问题(id,user_id,question)
投票(id,question_id)
我将如何编写
的SQL查询用户名|总票数(desc)
答案 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