匿名用户mysql 如何匹配多个 like 条件?
有一个tag表:
id tag
1 a,b,c
2 a,c,d
3 a
如何查询 tag 里包含 a 和 c 的? 也就是第一行和第二行
我来答
添加附件
收藏
分享
问题补充
4条回答
默认
最新
回答交流
提交
问题信息
请登录之后查看
邀请回答
暂无人订阅该标签,敬请期待~~
墨值悬赏
匿名用户有一个tag表:
id tag
1 a,b,c
2 a,c,d
3 a
如何查询 tag 里包含 a 和 c 的? 也就是第一行和第二行
select * from tag t where t.tag like ‘%a%c%’;
评论
有用 0楼上有缺陷,会查出 abc,b,d
评论
有用 0严谨的SQL写法来了
with cte as
(
select 1 as id,'a,b,c' as tag union all
select 2 as id,'a,c,d' as tag union all
select 3 as id,'a,d,e' as tag union all
select 4 as id,'c,d,e' as tag union all
select 5 as id,'a' as tag
)
select * from cte
where id in
(
select id from (
SELECT id,
SUBSTRING_INDEX(SUBSTRING_INDEX(tag,',',help_topic_id+1),',',-1) AS num
FROM
mysql.help_topic ,cte
WHERE
help_topic_id < LENGTH(tag)-LENGTH(REPLACE(tag,',',''))+1
) as t
where num ='a' or num = 'c'
group by id
having count(*) >=2
)
结果
id tag
1 a,b,c
2 a,c,d
评论
有用 0
墨值悬赏