2014-07-10 85 views
0

我有两个表中的一个说Employee与列作为需要联盟样的行为,而不使用查询/结果集的联盟

EmpId Name Class Region 
1  rr x  t 
2  tr v  g 

另一个表ConfidentalEmployee与列作为

EmpId(foreign key) Name 
1     rr 

现在必须写查询与员工表中的所有字段相关,但这些员工标识在ConfidentalEmployee表中,此类员工的详细信息(Class, Region)应为CAN'T DISCLOSE,如下所示:

EmpId Name Class    Region 
1  rr CAN'T DISCLOSE CAN'T DISCLOSE 
2  tr  v     g 

我可以使用基于EMPIds的连接使用两个查询并在结果集上执行联合。我的查询如下:

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 

但我想知道如果它可能与一个单一的查询没有联合操作?

回答

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 
0

你为什么试图避免一个联盟?这是他们的目的。

select EmpID 
    , Name 
    , Class 
    , Region 
from Employee 
union all 
select EmpID 
    , Name 
    , 'Can''t Disclose' 
    , 'Can''t Disclose' 
from ConfidentialEmployee 
order by EmpID 
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是适当的方法。

+0

尼斯,我的想法也是如此。 – wiesion

+0

你不需要雇员出席两个表。 –

+0

@LeonardoHerrera。 。 。这表明“机密员工”需要在两个表中,而不是全部员工。 –

0

如果我明白你的问题吧,我建议如下:

LEFT JOIN ConfidentalEmployee上EMPID,在select语句的使用情况,以检查是否ConfidentalEmployee.EmpId是NULL和别名“不能透露”为类和地区。