这是我的疑问:
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
和Accepted
的所有行的总和。
答案 0 :(得分: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
1}}。