MySQL 查寻条件使用正则 regexp

时间:2019-01-10
本文章向大家介绍MySQL 查寻条件使用正则 regexp,主要包括MySQL 查寻条件使用正则 regexp使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我用的是 Mybatis

t.hobby : 条件字段
hobby : 查寻参数,值可以是多个逗号分隔的值:‘阅读,交友,围棋’

<!-- t.hobby 的值最初可能是这样: '    阅读,  交友,围棋,足球  , 滑雪 ' 每个词的两边有空格不规则 -->
<!-- 下面逐步演示 -->
<if test="hobby!=null and hobby!=''">
	concat(',',REPLACE (t.hobby, ' ', ''),',') regexp concat(',(',replace(#{hobby},',','|'),'),')
</if>
<!-- 表字段 t.hobby 取出值 -->
<if test="hobby!=null and hobby!=''">
	concat(',',REPLACE ('    阅读,  交友,围棋,足球  , 滑雪 ', ' ', ''),',') regexp concat(',(',replace(#{hobby},',','|'),'),')
</if>
<!-- 表字段值处理后,去掉了多余的空格 -->
<if test="hobby!=null and hobby!=''">
	concat(',','阅读,交友,围棋,足球,滑雪',',') regexp concat(',(',replace(#{hobby},',','|'),'),')
</if>
<!-- concat后得到一个字符串,首尾加上了逗号 -->
<if test="hobby!=null and hobby!=''">
	',阅读,交友,围棋,足球,滑雪,' regexp concat(',(',replace(#{hobby},',','|'),'),')
</if>
<!-- 取出参数 #{hobby} 的值 -->
<if test="hobby!=null and hobby!=''">
	',阅读,交友,围棋,足球,滑雪,' regexp concat(',(',replace('阅读,交友,围棋',',','|'),'),')
</if>
<!-- 把逗号换成 |  -->
<if test="hobby!=null and hobby!=''">
	',阅读,交友,围棋,足球,滑雪,' regexp concat(',(','阅读|交友|围棋','),')
</if>
<!-- concat后得到一个字符串,首尾加上了括号,逗号  -->
<if test="hobby!=null and hobby!=''">
	',阅读,交友,围棋,足球,滑雪,' regexp ',(阅读|交友|围棋),'
</if>
得到结果是 1 作为条件就是真了。

复杂的过程主要是用来处理查寻条件。得到符合 regexp 格式的参数就ok了