SQL:使用第二个表中的单词列表搜索单元格



我在数据库中有两个表。

表A如下:

描述
黄色圆形 10
红色方块 20

这里我附加了两个查询。如果您只是想知道描述列是否包含球形或彩色列,那么请使用查询#2。

但若只想从TableA中选择行(若描述列包含球或彩色列中的任何内容(,则使用查询#1。

模式和插入语句:

create table tableA(description    varchar(50),value int);

insert into tableA values ('yellow round', 10);
insert into tableA values ('red squared', 20);

create table TableB (ball varchar(50),colored varchar(50));
insert into TableB values('round','red');
insert into TableB values('circular','blue');
insert into TableB values('globular','yellow');

查询#1:

select description,value, max(ball)ball,max(colored)colored
from 
(
select  a.*,(case when a.description like '%'+b.ball+'%' then 'true' else 'false' end) ball,
(case when a.description like '%'+b.colored+'%' then 'yes' else 'no' end) colored
from tableA a 
inner join TableB b on a.description like '%'+b.ball+'%' or a.description like '%'+b.colored+'%'
)t
group by  description,value

输出:

rue是
描述ball
黄色圆形10
红色方块20

我相信一个简单的caseexists就是您所需要的

select *,
case when exists (select * from tableb b where a.description like concat('%',b.ball,'%') then 'true' else 'false' end as ball,
case when exists (select * from tableb b where a.description like concat('%',b.colored,'%') then 'Yes' else 'No' end as colored
from tablea a

最新更新