我需要从数据库中的多个表中获取数据,我需要使用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
答案 0 :(得分:1)
我在这里稍微跳了一下枪(我会继续考虑以防止这种直觉反应错误),但诀窍可能是在内部使用“null if false”评估 / em> count()函数,is documented to only count non-null values:
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