mysql regexp匹配多个字符串

项目场景:

数据结构

其中nameArr存储的是名字集合,现在的需求是传入"aaa","fff",需要把包含这两个name的数据都查出来。


解决方案:

可以使用REGEXP来匹配包含多个特定ID的字符串。使用以下正则表达式:

sql 复制代码
select * from test
where nameArr regexp '"aaa"|"fff"'

使用mybatis实现

mapper

java 复制代码
/**
 * 正则匹配多个id字符串
 */
List<TestEntity> list(@Param("ids") List<String> ids);

xml

XML 复制代码
<select id="list" resultType="com.test.TestEntity">
	select * from test
	<if test="ids != null and ids.size()>0">
		and nameArr regexp concat('"',
		concat_ws('"|"',
		<foreach collection="ids" item="item" separator=",">
			#{item}
		</foreach>
		),'"')
	</if>
</select>

解析一下这个sql

ids这个集合会循环逗号拼接,打印sql

sql 复制代码
select * from test
where nameArr regexp concat('"',concat_ws('"|"','aaa','fff'),'"')

最终的sql

sql 复制代码
select * from test
where nameArr regexp '"aaa"|"fff"'
相关推荐
逝水如流年轻往返染尘32 分钟前
MySQL中的内置函数
数据库·mysql
咖啡啡不加糖1 小时前
深入理解MySQL死锁:从原理、案例到解决方案
java·数据库·mysql
开挖掘机上班3 小时前
mysql已经安装,但是通过rpm -q 没有找mysql相关的已安装包
数据库·mysql
花月C3 小时前
Mysql-定时删除数据库中的验证码
数据库·后端·mysql·spring
@小红花7 小时前
MySQL数据库从0到1
数据库·mysql·oracle
[听得时光枕水眠]8 小时前
MySQL基础(三)DQL(Data Query Language,数据查询语言)
数据库·mysql·oracle
bing_15811 小时前
跨多个微服务使用 Redis 共享数据时,如何管理数据一致性?
redis·微服务·mybatis
一只叫煤球的猫11 小时前
MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
后端·sql·mysql