MySQL查询计数返回错误的值

时间:2014-12-09 13:18:33

标签: mysql

因此,即使没有与list相关的任务,此查询也会返回结果1。如何解决它,以便为零任务的列表返回0?

SELECT 
  l.list_id, l.list_name, l.list_time_created, 
  COUNT(CASE WHEN t.task_id IS NULL THEN 0 ELSE 1 END) AS numberOfTasks,
  SUM(CASE WHEN t.task_completed IS NULL THEN 0 ELSE t.task_completed END) AS numberOfCompletedTasks
FROM list l
LEFT JOIN task t ON l.list_id = t.list_id 
WHERE l.user_id = ':user_id'
GROUP BY l.list_id;

1 个答案:

答案 0 :(得分:1)

如果没有任务,则会过滤掉这些行。你想要一个left join

SELECT l.list_id, l.list_name, l.list_time_created,
       COUNT(t.task_id ) AS numberofTasks,
       SUM(t.task_completed = 1) AS numberofCompletedTasks
FROM list l LEFT JOIN
     task t
     ON l.list_id = t.list_id 
WHERE l.user_id = ':user_id'
GROUP BY l.list_id;

我介绍了表别名。这些使查询更容易编写和阅读。

我还简化了numberofCompletedTasks的逻辑。你的原始配方很好(甚至是标准的SQL),但MySQL有一个很好的捷径。