2014-07-10 86 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和別名「不能透露」爲類和地區。