简体   繁体   中英

SQL Server 2012 How to determine if all the values in table A are in table B

I have two tables (A & B) that share a common value (Color), both tables can have any number of rows. I am trying to find a way to determine if all the distinct 'Colors' in table A exist in table B:

I have tried using EXCEPT, which almost works, unfortunately it returns false when table B has more Colors than table A, which is irrelevant all i care about is if every distinct Color from table A is in table B. I have been fiddling with both EXISTS and IN but can't see to get the correct results

declare @TableA table (Color varchar(10))
declare @TableB table (Color varchar(10))

insert into @TableA(Color) values ('red')
insert into @TableA(Color) values ('blue')
insert into @TableA(Color) values ('green')
--insert into @TableA(Color) values ('orange')


insert into @TableB(Color) values ('red')
insert into @TableB(Color) values ('blue')
insert into @TableB(Color) values ('green')
insert into @TableB(Color) values ('yellow')
insert into @TableB(Color) values ('purple')

IF NOT EXISTS (
    SELECT Color FROM @TableA
    EXCEPT
    SELECT Color FROM @TableB
)
SELECT 'true'
ELSE SELECT 'false'

I would like the above code to yield 'true'.

IF table A Colors > table B Colors THEN false
IF table A Colors <= table B Colors THEN true.

There are many ways to accomplish this. You could use a left join for this pretty easily.

if exists
(
    SELECT a.Color 
    FROM @TableA a
    left join @TableB b on b.Color = a.Color
    where b.Color is null
) 
    select 'Some Colors in A are not in B'
else
    select 'ALL Colors in A exist in B'

you could also just use your existing query and add DISTINCT:

IF NOT EXISTS (
    SELECT DISTINCT Color FROM @TableA
    EXCEPT
    SELECT DISTINCT Color FROM @TableB
)
SELECT 'true'
ELSE SELECT 'false'

Another way can be to compare the count of distinct elements in TableA against the count of distinct element in the INNER JOIN between TableA and TableB

This is far from being an optimized solution, but it works.

SELECT
CASE WHEN (SELECT COUNT(*)
    FROM
    (
        SELECT a.Color
        FROM @TableA a
        INNER JOIN @TableB b
        ON a.Color = b.Color
        GROUP BY a.Color
    ) T1) = (SELECT COUNT(*)
    FROM
    (
        SELECT a.Color
        FROM @TableA a
        GROUP BY a.Color
    ) T2)
    THEN 'true'
    ELSE 'false'
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM