我有以下问题,以确定在一个项目中是否缺少具有特定工作角色的用户:
表1:
ID | Project_ID
---+------------
1 | 11A
1 | 11B
1 | 11C
2 | 12B
2 | 12C
3 | 13A
3 | 13C
表2:
Project_ID | JobRole_ID
-------------+------------
11A | A
11B | B
11C | C
12B | B
12C | C
13A | A
13C | C
表3:
JobRole_ID | JobRole
-----------+---------
A | Manager
B | Project Leader
C | Project Assistent
对于每个项目,职位A,B和C都是必需的(表3)。表2仅包含添加的JobRoles,而不是缺少的。
我的期望是:
ID | JobRole
---+---------
1 | Manager
2 | NULL
3 | Manager
请帮帮我! THX
答案 0 :(得分:0)
您希望找到存在与此特定项目无关的JobRole的项目。
从头到尾:
--try to find projects
SELECT
T1.Id
FROM
Table1 AS T1
WHERE
--with at least one role
EXISTS(
SELECT
*
FROM
Table3 AS T3
WHERE
--where mapping does not exist
NOT EXISTS(
SELECT
*
FROM
Table2 AS T2
WHERE
T2.Project_ID = T1.Project_ID AND
T2.JobRole_ID = T3.JobRole_ID
)
)
修改强>
这可能是你想要的吗?如果没有,请您提供更多详细信息?
SELECT
T1.Id, T3.JobRole_ID
FROM
Table1 AS T1 LEFT JOIN
Table2 AS T2 ON T2.Project_ID = T1.Project_ID LEFT JOIN
Table3 AS T3 ON T3.JobRole_ID = T2.JobRole_ID
答案 1 :(得分:0)
这是一种方法:
select p.*, j.*
from projects p cross join
jobroles j left join
projectjobs pj
on p.project_id = pj.project_id and
j.jobrole_id = pj.jobrole_id
where pj.project_id is null;
它会生成所有项目和所有作业的列表(使用cross join
)。然后,使用left join
和where
子句筛选出存在的子句。
编辑:
您可以尝试使用逗号:
select p.*, j.*
from projects p,
jobroles j left join
projectjobs pj
on p.project_id = pj.project_id and
j.jobrole_id = pj.jobrole_id
where pj.project_id is null;
但是这可能不起作用,因为在from
子句中如何解析逗号的语义。您可能需要子查询:
select xpj.*
from (select p.*, j.*
from projects p, jobroles j
) xpj left join
projectjobs pj
on xpj.project_id = pj.project_id and
xpj.jobrole_id = pj.jobrole_id
where pj.project_id is null;
答案 2 :(得分:0)
根据您更新的要求,这应该有效,但我确信它可以简化。
select a.ID, b.JobRole
from (
select * from Table1, table3 where JobRole_ID = 'A'
) a left join (
select t1.id, t3.jobrole
from table1 t1
left join table2 t2 on t2.project_id = t1.project_id
left join table3 t3 on t3.jobrole_id = t2.jobrole_id
) b on a.id = b.id and a.jobrole = b.jobrole
group by a.ID, b.JobRole