如果第一个表的所有记录都存在于第二个表中,则返回true

时间:2012-03-16 12:12:44

标签: sql sql-server-2008 tsql

我有两张桌子:

declare @t1 table (id int)
declare @t2 table (id int)


insert into @t1
select 1 union select 3 union select 7

insert into @t2
select 1 union select 3 union select 7 union select 9 union select 4

select count(*) from @t1 t inner join @t2 t1 on t.id = t1.id

我得到上述查询的结果为3.如果t1中的所有记录都存在于t2中,则需要true或false。

这是真实表结构的简化示例。真正的表可能有数百万条记录,所以请让我知道一些优化的方法

5 个答案:

答案 0 :(得分:2)

SELECT CASE 
         WHEN EXISTS (SELECT id 
                      FROM   @t1 
                      EXCEPT 
                      SELECT id 
                      FROM   @t2) THEN 0 
         ELSE 1 
       END 

答案 1 :(得分:1)

declare @t1 table (id int)
declare @t2 table (id int)

insert into @t1
select 1 union select 3 union select 7

insert into @t2
select 1 union select 3 union select 7 union select 9 union select 4

if exists(
   select id from @t2
   except
   select id from @t1
)    print 'false'
else print 'all the records in t1 exists in t2'

答案 2 :(得分:1)

使用exists(可能会更有效率):

select
    case
        when not exists (select 1
            from @t1 t1
            where not exists(select 1 from @t2 t2 where t2.id = t1.id))
            then cast(1 as bit)
        else cast(0 as bit)
    end

答案 3 :(得分:1)

SELECT (CASE WHEN 
              (SELECT COUNT(*) from t1 where 
                  not id IN (select id from t2)) = 0 THEN 
                  convert(bit, 1) 
             ELSE convert(bit, 0) END) 

答案 4 :(得分:1)

将匹配行数与@t1中的总行数进行比较可能会更有效。有时您只需要尝试多种方法并查看查询计划,以查看哪种方法最适合您的情况。您需要一些具有相似数据量和适当索引的测试表等。

declare @t1 table (id int) 
declare @t2 table (id int) 

insert into @t1 
select 1 union select 3 union select 7

insert into @t2 
select 1 union select 3 union select 7 union select 9 union select 4 

select case 
  when (select count(*) from @t1 t join @t2 t1 on t.id = t1.id) = 
       (select count(*) from @t1) then 1 else 0
  end as rows_match