1

我需要从数据库的多个表中获取数据,并且需要使用 1 个查询。我遇到的麻烦是我需要计算每个项目有多少任务以及完成了多少任务。

我得到了这些表:
项目:

id    name        start_date           end_date             project_leader    finished
1     project_1   2012-08-01 00:00:00  2012-29-01 00:00:00  2                 0

用户

id    username    password    email      status
1     user_1      pass_1      email_1    1
2     user_2      pass_2      email_2    1

user_has_project

userid   projectId
1        1

任务

id   project  description          end_date               user  finished
1    1        test description 1   2012-29-01 00:00:00    1     1
2    1        test description 2   2012-29-01 00:00:00    1     0

所以我需要做的是做一个查询,应该给我这个结果:
想要的结果:

project_id  project_name    start_date           end_date             project_leader    finished       tasks      finished_tasks
1           project_1       2012-08-01 00:00:00  2012-29-01 00:00:00  user_2            0              2          1

我让它工作,直到我需要计算已完成任务数量的部分。到目前为止,我得到了这个查询,但它还没有计算完成的任务。我怎样才能做到这一点?

询问:

SELECT projects.id,
       projects.name,
       projects.start_date,
       projects.end_date,
       projects.finished,
       users.username AS project_leader,
       COUNT(tasks.id) AS tasks
FROM projects
LEFT JOIN tasks ON (tasks.project = projects.id)
JOIN user_has_project ON (user_has_project.projectId = projects.id)
JOIN users ON (projects.project_leader = users.id)
WHERE user_has_project.userId = 1
GROUP BY projects.id
4

1 回答 1

1

我在这里有点过激(我会继续考虑以防这种直觉反应是错误的),但诀窍可能是在 count() 函数中使用“ null if false ”评估,这已记录在案只计算非空值

SELECT projects.id,
       projects.name,
       projects.start_date,
       projects.end_date,
       projects.finished,
       users.username AS project_leader,
       COUNT(tasks.id) AS tasks,
       COUNT(NULLIF(tasks.finished, 0)) as finished_tasks
于 2012-08-25T17:56:22.600 回答