Return true if all records of the first table exist in the second table
I have two tables:
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
I get the result for the above query as 3. I need true or false if all records in t1 exist in t2.
this is a simplified example of a real table structure. real tables can have millions of records, so please let me know some optimized way to do this.
+3
source to share
5 answers
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'
+1
source to share
Comparing the number of matched lines to full lines in @t1
may be more efficient. Sometimes, you just need to try several methods and look at the query plans to see which one works best for your situation. You will need multiple test tables with similar amounts of data and corresponding indexes, etc.
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
+1
source to share