2010-07-22 111 views
3

我想要一個查詢產生以下結果..查詢與加入3個表

導致了在表1和表2中,並沒有在表3的記錄。

每個表中有超過10,000條記錄..所以我正在尋找一個有效的。在所有的表Cono是主鍵..

詳細的表。

表1: -

Cono  

th-123 
th-124 
th-125 

表2: -

Cono  

th-234 
th-245 
th-256 

表3: -

Cono  

th-124 
th-125 
th-256 

現在我想有FOLL由於記錄

結果表: -

Cono  

th-123 
th-234 
th-245 

回答

3

試試這個

WITH Table1 AS 
(
    SELECT 'th-123' CONO UNION 
    SELECT 'th-124' UNION 
    SELECT 'th-125' 
) 
, 
Table2 AS 
(
    SELECT 'th-234' CONO UNION 
    SELECT 'th-245' UNION 
    SELECT 'th-256' 
) 
, 
Table3 AS 
(
    SELECT 'th-124' CONO UNION 
    SELECT 'th-125' UNION 
    SELECT 'th-256' 
) 

SELECT CONO 
FROM Table1 
WHERE NOT EXISTS 
(
    SELECT 1 
    FROM Table3 
    WHERE TABLE1.CONO = TABLE3.CONO 
) 

UNION ALL 

SELECT CONO 
FROM Table2 
WHERE NOT EXISTS 
(
    SELECT 1 
    FROM Table3 
    WHERE TABLE2.CONO = TABLE3.CONO 
) 
+0

我們可以在這種情況下使用UNION ALL – 2010-07-22 12:54:56

+0

@Vash Tx。回答編輯。 – 2010-07-22 12:57:44

+0

@Vash,你基於什麼假設'我們可以在這種情況下使用UNION ALL'?對於OP的簡單示例數據,「UNION ALL」可以工作,但它是否會成爲生產中的正確方式?誰知道。我寧願使用它,因爲它速度更快,但我不打算做出這樣的假設,除非OP提供更多信息。 – 2010-07-22 13:03:10

1

試試這個:

select t.cono from Table1 t WHERE NOT EXISTS (SELECT 1 
               FROM Table3 x WHERE x.cono=t.cono) 
UNION 
select t.cono from Table2 t WHERE NOT EXISTS (SELECT 1 
               FROM Table3 x WHERE x.cono=t.cono) 
0

試試這個(未測試):

; WITH all_data AS (
    SELECT * FROM table1 
    UNION ALL 
    SELECT * FROM table2 
) 
SELECT * 
FROM all_data ad 
WHERE NOT EXISTS (
    SELECT * 
    FROM table3 t3 
    WHERE ad.Cono = t3.Cono); 
模糊表和名稱的
0

種類,但這裏是你可以做什麼,如果你真的想這樣做在一個查詢:

SELECT Cono 
FROM Table3 
WHERE NOT EXISTS (SELECT Cono 
        FROM TABLE1 as T 
        WHERE EXISTS (SELECT * 
            FROM TABLE2 
            WHERE T.Cono = TABLE2.Cono)); 

這應該選擇在表3中沒有查詢存在的價值是括號中被創造,這是在表1和表2

不幸的是,築巢和效率通常不走手牽手行由表...

1
(SELECT t1.Cono FROM table1 t1 
LEFT JOIN table3 t3 
ON t3.Cono = t1.Cono 
WHERE t3.Cono IS NULL) 
UNION ALL 
(SELECT t2.Cono FROM table2 t2 
LEFT JOIN table3 t3 
ON t3.Cono = t2.Cono 
WHERE t3.Cono IS NULL) 
+0

'exists'會比'left join'更快,'UNION ALL'也可能會產生重複,OP的數據還沒有被足夠的解釋以假定table1.cono和table2.cono的值不會重疊。 – 2010-07-22 17:15:49

+0

@KM,請提供參考,說明存在速度更快。 – 2010-07-22 17:44:00

+0

看到這篇文章:http://explainextended.com/2009/06/16/in-vs-join-vs-exists/它基本上說,聯接和EXISTS有時會有相同的執行計劃,有時不會。但是,當他們不EXISTS會稍微快一點。 – 2010-07-22 20:00:35

0

這個 爲我工作......並快速處理:

select X.FID, c.id as CID 
from 
(
    select a.id as FID from tbl1 a 
    union 
    select b.id as FID from tbl2 b 
) as X 
left outer join tbl3 c on FID = c.id 
where 
    c.id is null 
;