SQL-使用 if exist 匹配 table 中的两列

SQL-using if exist in matching two columns in table

我正在尝试使用洗涤剂、肥皂、洗碗等关键字来匹配我的 sql table 中的两列,如果关键字在两列中找到匹配项,我希望另一列说它是匹配的。我打算使用 if exist 但我不知道正确的语法。

示例列:

Column1                Column2
-----------------------------------------------
detergent powder       all powder detergent
dish washing liquid    dish liquid for washing 
hand soap              hand liquid soap

这是您问题的最简单的解决方案。诀窍在于我们在 select 语句中创建的别名为 Match 的 "virtual" 列。此列是使用 case 语句计算的,以查看搜索词是否出现在两列中。请注意,我们需要使用带有通配符 %.

like 语句
create table Example (Column1 varchar(max), Column2 varchar(max));
insert into Example select 'detergent powder', 'all powder detergent';
insert into Example select 'dish washing liquid', 'dish liquid for washing' ;
insert into Example select 'hand soap', 'hand liquid soap';

declare @search varchar(20) = 'detergent';

select  Column1, 
        Column2, 
        case when Column1 like '%' + @search + '%' and 
                  Column2 like '%' + @search + '%' 
             then 'matched' 
             else 'not matched' end as [Match] 
from Example;

我们还可以创建 Match 列作为 table 中的 "real" 列,并稍微修改此脚本以 update 该列基于相同的标准。

这是一个检查 3 个词中的任何一个是否出现在两列中的示例。

示例数据:

CREATE TABLE Test (
 Id INT IDENTITY(1,1) PRIMARY KEY,
 Col1 VARCHAR(100), 
 Col2 VARCHAR(100)
);

INSERT INTO Test (Col1, Col2) VALUES
('detergent powder', 'all powder detergent'),
('dish washing liquid', 'dish liquid for washing'),
('hand soap', 'hand liquid soap'),
('soap dish', 'detergent');

查询:

SELECT  t.*
 , cast(
      case 
      when exists (
           select 1 
           from (values ('soap'),('detergent'),('dish')) s(search)
           join (values (Col1),(Col2)) c(col)
           on c.col like '%'+s.search+'%'
           group by s.search
           having count(*) = 2
     ) then 1 else 0 end as bit) as hasMatch
FROM Test t;

EXISTS 检查查询是否至少有 1 个结果。
HAVING 子句确保每个搜索词需要 2 个匹配项。

但没有 GROUP BY & HAVING 子句也可以做到:

SELECT  t.*
 , cast(case when exists (
           select 1 
           from (values ('soap'),('detergent'),('dish')) s(search)
           where Col1 like '%'+s.search+'%'
             and Col2 like '%'+s.search+'%'
     ) then 1 else 0 end as bit) as hasMatch
FROM Test t;

rextester 测试 here