gpt4 book ai didi

SQL Server 2012 如何判断表A中的所有值是否在表B中

转载 作者:行者123 更新时间:2023-12-02 00:52:20 25 4
gpt4 key购买 nike

我有两个表(A 和 B)共享一个公共(public)值(颜色),两个表都可以有任意数量的行。我正在尝试找到一种方法来确定表 A 中的所有不同“颜色”是否存在于表 B 中:

我尝试过使用 EXCEPT,它几乎可以工作,不幸的是,当表 B 的颜色比表 A 多时它返回 false,这是无关紧要的,我只关心表 A 中的每个不同颜色是否在表 B 中。我一直摆弄 EXISTS 和 IN 但看不到得到正确的结果

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'

我希望上面的代码产生“真”。

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

最佳答案

有很多方法可以做到这一点。您可以很容易地为此使用左连接。

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'

关于SQL Server 2012 如何判断表A中的所有值是否在表B中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56669020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com