我有两个表格Employee
,其中列为
EmpId Name Class Region
1 rr x t
2 tr v g
另一个表ConfidentalEmployee
,其中列为
EmpId(foreign key) Name
1 rr
现在必须使用Employee表的所有字段编写查询,但这些Employee的Id在ConfidentalEmployee表中,此类员工的详细信息(Class, Region
)应为CAN'T DISCLOSE
,如下所示:
EmpId Name Class Region
1 rr CAN'T DISCLOSE CAN'T DISCLOSE
2 tr v g
我可以使用两个基于EMPId的连接查询来执行此操作,并对结果集执行联合。我的查询如下:
select e.EmpId, e.Name,e.Class,e.Region from Employee e inner join ConfidentalEmployee ce on e.EmpId <> ce.EmpId
UNION
select e.EmpId, e.Name,'CAN'T DISCLOSE' as Class, 'CAN'T DISCLOSE' as Region from Employee e inner join ConfidentalEmployee ce on e.EmpId = ce.EmpId
但是我想知道是否可以使用单个查询而不进行联合操作?
答案 0 :(得分:2)
您可以尝试此查询
SELECT Emp.EmptId, Emp.Name,
CASE WHEN CEmp.EmpId IS NULL THEN Emp.Class ELSE 'CAN''T DISCLOSE' END AS Class,
CASE WHEN CEmp.EmpId IS NULL THEN Emp.Region ELSE 'CAN''T DISCLOSE' END AS Region
FROM Employee AS Emp
LEFT JOIN ConfidentialEmployee CEmp ON Emp.EmpId = CEmp.EmpId
答案 1 :(得分:1)
您想要加入,特别是left outer join
并检查匹配项:
select e.EmpId, coalesce(ce.Name, e.Name) as Name,
(case when ce.empid is not null then 'CAN''T DISCLOSE' else e.Class end) as class,
(case when ce.empid is not null then 'CAN''T DISCLOSE' else e.Region end) as region
from employee e left outer join
confidentialemployee ce
on e.empid = ce.empid;
这假设机密员工在两个表中,如您问题中的示例所示。否则,union all
是适当的方法。
答案 2 :(得分:0)
你为什么要避免使用UNION?这就是他们的目的。
select EmpID
, Name
, Class
, Region
from Employee
union all
select EmpID
, Name
, 'Can''t Disclose'
, 'Can''t Disclose'
from ConfidentialEmployee
order by EmpID
答案 3 :(得分:0)
如果我理解你的问题,我建议如下:
在EmpId上左连接ConfidentalEmployee,在select语句中使用CASE来检查ConfidentalEmployee.EmpId是否为NULL和别名&#34; CAN&#39; T DISCLOSE&#34;作为阶级和地区。