SQL查询:返回A中不在B中的所有行以及其他标准

时间:2015-03-04 22:43:41

标签: sql-server

我正在使用SQL Server 2008.我的目标是查找表A中不在表B中的所有行。我还想查找表A中表示符合表B中两个特定条件的所有行。我对第一部分的基本查询是:

SELECT
table_A.some_col
FROM table_A
LEFT JOIN table_B
ON table_A.A_key = table_B.B_key
WHERE
table_B.B_key IS NULL

要获得第二部分,我最好的猜测是:

SELECT
table_A.some_col
FROM table_A
LEFT JOIN table_B
ON table_A.A_key = table_B.B_key
WHERE
table_B.B_key IS NULL
OR
table_B.another_col = 'some_value'
OR
table_B.yet_another_col = 'some_other_value'

然而,这给了我比预期更多的行返回。我是否需要通过使用UNION来解决这个问题?

1 个答案:

答案 0 :(得分:0)

SELECT
table_A.some_col
FROM table_A

where not exists
(  select * from table_B
where /* relationship */ table_A.A_key = table_B.B_key and  /* any conditions you want */ table_B.B_key IS NULL and table_B.ColX = 'abc' )

OR

SELECT
table_A.some_col
FROM table_A

where not exists
(  select * from table_B
where /* relationship */ table_A.A_key = table_B.B_key )

UNION ALL

    SELECT
table_A.some_col
FROM table_A

where exists
(  select * from table_B
where table_B.B_key IS NULL and table_B.ColX = 'abc' )

发布一些DDL,一些样本INSERTS和预期结果,如果你想要更多定义。