Project Accomplishment
------- ---------------
id id
project_name accomplishment_name
project_status_id project_id
accomplishment_status_id
一个项目可以有许多成就;一个成就只能有1个项目。
到目前为止,我有一个非常基本的查询,但是我对子查询或最有效的方式并不十分熟悉。我尝试按状态对项目的所有成就进行计数,然后尝试进行数学运算以确定状态3是否等于成就的总数,但这感觉超级高效。
这是我目前拥有的:
SELECT p.id, p.name, COUNT(a) AS active_accomp_count FROM habits4.accomplishment a
join habits4.project p ON p.id = a.project_id
WHERE a.accomp_status_id = 1
GROUP BY p.id
SELECT p.id, p.name, count(a) AS completed_accomp_count FROM habits4.accomplishment a
JOIN habits4.project p ON p.id = a.project_id
WHERE a.accomp_status_id = 2
GROUP BY p.id
SELECT p.id, p.name, COUNT(a) AS inactive_accomp_count FROM habits4.accomplishment a
JOIN habits4.project p ON p.id = a.project_id
WHERE a.accomp_status_id = 3
GROUP BY p.id
我希望输出显示所有仅具有其所有关联成就状态= 3的所有项目的Project_ID和Project_name。
示例数据:
Project 1 Project 2
----------------- -----------------
Accomplishment 1 Accomplishment 5
status = 1 status = 3
Accomplishment 2 Accomplishment 6
status = 1 status = 3
Accomplishment 3
status = 2
成就4 状态= 3 `
项目2应该显示在输出中,因为它只有状态为3的成就。 项目1不应在输出中显示,因为尽管它确实具有状态为3的成就,但它也具有状态不是3的成就。
答案 0 :(得分:1)
所以您想要满足两个条件的项目。
status = 3
的一项成就通过内部联接和分组依据,第一个很容易。 结合两个条件很简单。 因此,让我们从选择除status = 3之外没有其他成就的所有项目开始。
如果我们想要没有成就的项目,则可以执行左外部联接并选择从外部联接创建的具有NULL的记录。
SELECT p.id, p.name, COUNT(a) AS inactive_accomp_count
FROM habits4.project p
LEFT OUTER JOIN habits4.accomplishment a ON p.id = a.project_id
WHERE a.id IS NULL
GROUP BY p.id, p.name
然后将其与状态为3的项目所需的内部联接相结合,
SELECT p.id, p.name, COUNT(a) AS inactive_accomp_count
FROM habits4.project p
INNER JOIN habits4.accomplishment a ON p.id = a.project_id
WHERE a.accomp_status_id = 3
所以我们在一起:
SELECT p.id AS inactive_accomp_count
FROM habits4.project p1
INNER JOIN habits4.accomplishment a1 ON p1.id = a1.project_id
INNER JOIN habits4.project p2 ON p1.id = p2.id
LEFT OUTER JOIN habits4.accomplishment a2 ON p2.id = a2.project_id
WHERE a2.id IS NULL
GROUP BY p1.id
这将为您提供正确的项目,但由于我们在记录组中做的太多,所以计数将被弄乱。因此,将其用作子选择,然后编写外部查询以正确计数记录。