如何只显示字符串之间完全不匹配的行?

How to show only rows where there is no match between strings at all?

我必须比较两列,并且只能提取字符串之间甚至没有部分匹配的行。例如,我有这个 table:

Col1 Col2
John Smith John Smith ltd
Pepper Row Whatever Pepper
red Blue

过滤后我应该看到的唯一一行是最后一行:

Col1 Col2
red Blue

我找到了一个答案 here,它显示了部分匹配的结果。我尝试使用 NOT LIKE 将其修改为 return 只有 0 个匹配项,但没有成功。

如果你只想拆分 col1 单词并想检查它是否存在于 col2 中,为此你可以尝试如下。

select col1,col2 from mytable
except   
select col1,col2 from mytable t
cross apply
(
 select * from string_split(t.Col1,' ')
)x    
where col2  like  '%' + [value] + '%'  

注意string_split 将在 SQL Server 2017+ 上运行,如果您使用的是旧版本,则需要使用一些自定义拆分功能。

如果您想要 none 个单词重叠的行,您可以使用 not exists 子句:

select t.*
from t
where not exists (select 1
                  from string_split(t.col1, ' ') s1 join
                       string_split(t.col2, ' ') s2
                       on s1.value = s2.value
                 );

注意:此公式允许您 return 整行 -- 即未包含在比较中的其他列。

如果您使用的是不支持 string_split() 的 SQL 服务器的旧版本,我建议您查找执行相同操作的用户定义函数的代码。