8

我需要知道一个表中的所有行是否存在于另一个表中:

declare @Table1 table (id int)
declare @Table2 table (id int)

insert into @Table1(id) values (1)
insert into @Table1(id) values (4)
insert into @Table1(id) values (5)


insert into @Table2(id) values (1)
insert into @Table2(id) values (2)
insert into @Table2(id) values (3)

if exists (select id from @Table1 where id in (select id from @Table2))
    select 'yes exists'
else
    select 'no, doesn''t exist' 

此查询返回yes exists但应该返回no, doesn't exist,因为 1 中仅存在 1 @Table2,值 4 和 5 不存在。

我应该在查询中更改什么?谢谢!

4

4 回答 4

9
IF NOT EXISTS (
    SELECT ID FROM @Table1
    EXCEPT
    SELECT ID FROM @Table2
)
SELECT 'yes exists'
ELSE SELECT 'no, doesn''t exist'
于 2012-04-27T15:56:31.337 回答
2

您可以使用EXCEPT来获取两个表的设置差异。如果返回任何 ID,则两个表不相等:

SELECT ID
FROM @Table1
EXCEPT 
SELECT ID
FROM @Table2

EXCEPT 返回左侧查询中未在右侧查询中找到的任何不同值。

所以,要让你的“不,不存在”

;WITH diff AS(
    SELECT ID
    FROM @Table1
    EXCEPT 
    SELECT ID
    FROM @Table2
)
SELECT CASE WHEN COUNT(diff.ID) = 0 
         THEN 'yes exists'
         ELSE 'no, doesnt exist'
         END AS Result
FROM diff
于 2012-04-27T15:57:27.517 回答
0
select case when count(*) > 0 then 'no' else 'yes' end as AllExist
from @Table1 t1
left outer join @Table2 t2 on t1.id = t2.id
where t2.id is null
于 2012-04-27T15:55:02.567 回答
0

只要两个 id 列都是唯一的(如果它们是 id,它们应该是唯一的),这将起作用

DECLARE @totalRows int;
SET @totalRows = SELECT count(*) from Table1;

RETURN (@totalRows == SELECT count(*) from Table1 JOIN Table2 on Table1.id = Table2.id)
于 2012-04-27T15:55:09.137 回答