我有这个问题:
SELECT
SUM(IF(b.correct = 1,1,0)) correct_answers,
SUM(IF(b.correct != 1,1,0)) incorrect_answers,
SUM(IF(a.answer IS NULL) 1,0)) as no_answers,
a.ID
FROM `a` join b on a.answer = b.id
where a.created_at between '2014-06-10' and '2014-06-17'
group by a.ID order by correct_answers desc
基本上我试图获取每个用户测验的正确,不正确和无答案的数量。所以我得到了正确和错误的计数。但是当我尝试计算无答案的数量时(表a中的答案列为NULL)我得到全部为零。这个查询有什么问题吗?
答案 0 :(得分:2)
试试这个:
SELECT SUM(b.correct = 1) correct_answers,
SUM(b.correct != 1) incorrect_answers,
SUM(a.answer IS NULL) AS no_answers,
a.ID
FROM a
LEFT JOIN b ON a.answer = b.id
WHERE a.created_at BETWEEN '2014-06-10' AND '2014-06-17'
GROUP BY a.ID
ORDER BY SUM(b.correct = 1) DESC;
答案 1 :(得分:0)
你错过了一个','在第3行
更改:
SUM(IF(a.answer IS NULL) 1,0)) as no_answers,
要:
SUM(IF(a.answer IS NULL, 1,0)) as no_answers,
答案 2 :(得分:0)
纠正这个
SUM(IF(a.answer IS NULL), 1,0)) as no_answers
而不是
SUM(IF(a.answer IS NULL) 1,0)) as no_answers
答案 3 :(得分:0)
您的查询对于您所描述的内容看起来是正确的。这是一个可能的简化以及left join
:
SELECT SUM(b.correct = 1) correct_answers,
SUM(b.correct <> 1) incorrect_answers,
SUM(a.answer IS NULL) as no_answers,
a.ID
FROM `a` left join
b
on a.answer = b.id
where a.created_at between '2014-06-10' and '2014-06-17'
group by a.ID
order by correct_answers desc;
MySQL中不需要if
语句。
答案 4 :(得分:0)
SELECT
SUM(IF(b.correct = 1,1,0)) correct_answers,
SUM(IF(b.correct != 1,1,0)) incorrect_answers,
SUM(IF(a.answer IS NULL,1,0)) as no_answers, <-- You missed a comma here. So, it was always evaluating to 0.
a.ID
FROM `a` join b on a.answer = b.id
where a.created_at between '2014-06-10' and '2014-06-17'
group by a.ID order by correct_answers desc