这是我的查询:
SELECT usr.id,
count(DISTINCT sol.id) as 'Asked',
count(DISTINCT ans.id) as 'Answered',
sum(DISTINCT CASE ans.accepted WHEN 1 THEN 1 ELSE 0 end) as 'Accepted'
FROM tbl_users usr
LEFT JOIN tbl_solutions sol on sol.authorID = usr.id
LEFT JOIN tbl_solution_answers ans on ans.authorID = usr.id
group by usr.id, sol.authorID
我的上述查询与 sum(DISTINCT CASE ans.accepted WHEN 1 THEN 1 ELSE 0 end)
仅返回 1,尽管我知道情况并非如此。我尝试在 ans.authorID
上添加组子句,但没有效果。
如何获取 tbl_solution_answers ans
表中所有行的总和,其中 authorID
是 tbl_users.id
和 >已接受
为 1。
最佳答案
SELECT usr.id,
count(DISTINCT sol.id) as 'Asked',
count(DISTINCT ans.id) as 'Answered',
count(DISTINCT case ans.accepted when 1 then ans.id end) as 'Accepted'
FROM tbl_users usr
LEFT JOIN tbl_solutions sol on sol.authorID = usr.id
LEFT JOIN tbl_solution_answers ans on ans.authorID = usr.id
group by usr.id, sol.authorID, ans.authorID
经过这么多次排列count(DISTINCT case ans.accepted when 1 then ans.id end) as 'Accepted'
似乎有效。现在如果 authorID
在tbl_solution_answers
有 8 行,它们都将返回为 Answered
如果说其中 3 个是 Accepted
那么 3 返回为 Accepted
.
关于MySQL 派生表中列值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9091696/