多关键词模糊查询问题

凌云紫冥 2014-07-26 07:36:03
现有一张表car
id name type
0 长安CS75 SUV
还有一张表car_tag
id car_id tag_name
0 0 好看
1 0 炫酷
2 0 吊炸天
输入多个关键词,在car_tag里面匹配,将符合多个关键词的并集car数据找出来。
比如搜 好看、炫酷 能把上面表的数据找出来
搜好看、豪车 就搜不出来
请问这个sql该怎么写,多谢!


...全文
145 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
霜寒月冷 2014-07-27
  • 打赏
  • 举报
回复
试下我这个
if object_id('[tb]') is not null drop table [tb]
go
create table tb (id int,                car_id int,               tag_name varchar(20))

insert into tb
select '0','0','好看'union all         
select '1','0','炫酷'union all         
select '2','0','吊炸天'                
go
if object_id('[car]') is not null drop table [car]
create table car(id int ,name varchar(20),type  varchar(20))
insert into  car
select '0','长安CS75','SUV'

go
declare @s varchar(20)
set @s='好看、炫酷'
select car.name,tb.tag_name from tb   left join  car on  tb.id=car.id

where tag_name in
(
select distinct substring(@s,number ,charindex('、',@s+'、',number)-number) from master.dbo.spt_values 
where number>=1 and number<=len(@s)  and substring('、'+@s,number,1)='、')
唐诗三百首 2014-07-27
  • 打赏
  • 举报
回复
比如搜 好看、炫酷 能把上面表的数据找出来 --> 请问找出来的返回结果是怎么样的?
天堂的鸽子 2014-07-27
  • 打赏
  • 举报
回复
create table car
(id char(10),
name char(20),
typ char(20))

insert into car
values('0','长安CS75','SUV')

create table car_tag
(id char(10),
car_id char(20),
tag_name char(20))

insert into car_tag
values('0','0','好看'),
('1','0','炫酷'),
('2','0','吊炸天')

select distinct a.* from car a,car_tag b
where a.id=b.car_id and
exists (select * from car_tag c where c.car_id=b.car_id and c.tag_name like '%好看%')
and exists (select * from car_tag c where c.car_id=b.car_id and c.tag_name like '%豪车%')

select distinct a.* from car a,car_tag b
where a.id=b.car_id and
exists (select * from car_tag c where c.car_id=b.car_id and c.tag_name like '%好看%')
and exists (select * from car_tag c where c.car_id=b.car_id and c.tag_name like '%炫酷%')
结果图如下:
天堂的鸽子 2014-07-27
  • 打赏
  • 举报
回复
楼上的写法不对哦,不符合要求!———“比如搜 好看、炫酷 能把上面表的数据找出来; 搜好看、豪车 就搜不出来”
道玄希言 2014-07-26
  • 打赏
  • 举报
回复
select car.* , car_tag.name from car join car_tag on car.id = car_tag.car_id where (tag_name like '%关键字1%' or tag_name like '%关键字2%' or …… )

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧