我需要列出客户名称及其项目名称,其中有员工GLC
处理任务而不是员工CAC
处理任务。**
我尝试了以下内容,但得到了一个空集:
select
c.custname, p.pjtitle
from
(select taskno pjno
from task
where taskno not in
(select taskno
from task
where empid = 'CAC')
and empid = 'GLC') t
join project p on p.pjno = t.pjno
join customer c on p.custno = c.custno;
我应该如何正确使用join
和subquery
?
答案 0 :(得分:4)
SELECT c.custname, p.pjtitle
FROM customer c
JOIN project p ON p.custno = c.custno
JOIN task t ON p.pjno=t.pjno
WHERE t.empid='GLC'
AND NOT EXISTS (SELECT NULL FROM task t1 WHERE t.pjno=t1.pjno AND t1.empid='CAC')
;
答案 1 :(得分:2)
如果您需要客户名称和项目名称,那么您可能不希望重复。这是set-within-sets子查询的示例。我认为最好的解决方案是使用聚合,因为这为描述条件提供了最大的灵活性。
SELECT c.custname, p.pjtitle
FROM customer c join
project P
ON P.CUSTNO = P.CUSTNO join
task t ON t.pjno = p.pjno
group by c.custname, p.pjtitle
having sum(case when empid = 'GLC' > 0 then 1 else 0 end) > 0 and
sum(case when empid = 'CAC' > 0 then 1 else 0 end) = 0
having子句的两个部分是计算每个员工在特定项目上工作的次数。第一个说“确保GLC正在进行至少一次任务”,第二个说“确保CAC正在进行任务”。
答案 2 :(得分:0)
如果您只需要GLC员工的客户名称和项目,那么请使用以下查询
SELECT c.custname ,
p.pjtitle
FROM Customer AS c
INNER JOIN project AS p ON c.CUSTNO = p.CUSTNO
INNER JOIN task AS t ON p.PJNO = t.PJNO
WHERE t.EMPID = 'GLC'
如果您想要员工GLC和CAC,那么
SELECT c.custname ,
p.pjtitle
FROM Customer AS c
INNER JOIN project AS p ON c.CUSTNO = p.CUSTNO
INNER JOIN task AS t ON p.PJNO = t.PJNO
WHERE t.EMPID = 'GLC'
AND t.EMPID = 'CAC'
答案 3 :(得分:0)
试试这个:
SELECT c.custname, p.pjtitle
FROM customer AS c
JOIN project AS P ON P.CUSTNO = P.CUSTNO
JOIN tack AS t ON t.pjno = p.pjno
WHERE t.empid = 'GLC'
AND NOT EXISTS (SELECT NULL FROM TASK WHERE empid = 'GLC' AND empid = 'CAC');
答案 4 :(得分:0)
检查此答案是否有效
select c.custname, p.pjtitle
from project p, customer c where c.custno = p.custno
and exists
(select t.pjno from task t where t.empid = 'GLC' and p.pjno = t.pjno
and t.pjno not IN (select pjno from task where empid = 'CAC'))