2017-06-21 59 views
1

我想要做的兩個表像這些之間的減法運算:用在Oracle SQL固定列選擇減

表1:

employee_id | job | sector 
----------- | ------ | ------ 
10   | a  | 1 
10   | a  | 2 
10   | b  | 4 

表2:

job | sector 
---- | ------ 
a | 1 
a | 2 
a | 3 
b | 1 
b | 4 
c | 1 
c | 2 

並且因此我想,對於每個employee_id,{job,sector}在table1中都沒有連接。

結果:

employee_id | job | sector 
----------- | --- | ------ 
10   | a | 3 
10   | b | 1 
10   | c | 1 
10   | c | 2 

這可能嗎?

我希望我已經寫在一個清晰的方式!謝謝!

+0

你怎麼'employee_id'如果表沒有鏈接? –

+0

Employee_id是另一個稱爲Employee的表的FK。 –

回答

1

首先選擇完整的數據集,即EMPLOYEE_ID X工作/扇區。從這些中刪除現有的table1條目以獲取缺少的條目。 (我已經改名爲你的表table2job_sector以提高可讀性。我還假設你有一個employee表。)

select e.employee_id, js.job, js.sector 
from employee e 
cross join job_sector js 
minus 
select employee_id, job, sector 
from table1; 
+0

是的!有用!謝謝! –

+0

PS:你猜得好,我有'員工'表! –

0

LEFT JOIN,其中T2爲空

select t1.* 
from table1 t1 
let join table2 t2 
    on t1.job = t2.job 
    and t1.sector = t2.sector 
where t2.job is null 
0

這聽起來似乎只是一個left join(或not innot exists):

select 10 as employee_id, t2.* 
from table2 t2 left join 
    table1 t1 
    on t2.job = t1.job and t2.sector = t1.sector 
where t1.job is null; 

我對你如何獲得員工ID有點糊塗如果表格未鏈接

如果您在t1有多個員工,那麼你可以做:

select e.employee_id, t2.* 
from (select distinct employee_id from t1) e cross join 
    table2 t2 left join 
    table1 t1 
    on t2.job = t1.job and t2.sector = t1.sector and 
     e.employee_id = t1.employee_id 
where t1.job is null; 
+0

幹得好!我在t1有多個employee_id,你的第二個解決方案工作正常!謝謝! –

0

你可以簡單地做一個左加入實現它。您的查詢將是這個樣子:

SELECT T2.* 
FROM TABLE2 T2 LEFT JOIN 
    TABLE1 T1 
    ON T2.JOB = T1.JOB AND T2.SECTOR = T2.SECTOR 
WHERE T1.JOB IS NULL; 

雖然表必須以獲得員工ID鏈接。