查询连接3个表

时间:2010-07-22 12:47:35

标签: sql sql-server sql-server-2005

我想要一个查询来产生以下结果..

导致table1和table2中的记录不在table3中。<​​/ p>

每张桌子上有超过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

现在我想拥有以下记录

结果表: -

Cono     

th-123
th-234
th-245

6 个答案:

答案 0 :(得分: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
)

答案 1 :(得分: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)

答案 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)

答案 3 :(得分: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);

答案 4 :(得分: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中的行组成的表。

不幸的是,嵌套和效率通常不是齐头并进......

答案 5 :(得分: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
;