先看表结构和数据:
需求:
查询出manager_id中包含某些字符的数据,此处查询manager_id包含6651545956882725395,5722501350582149881的数据,
SQL语句如下:
1
2
3
4
5
|
SELECT t.* from bas_cm_customer t where position( '6651545956882725395' in t.manager_id) > 0 OR position ( '5722501350582149881' in t.manager_id) > 0; SELECT t.* from bas_cm_customer t where position( '6651545956882725395' in t.manager_id) > 0 OR position( '5722501350582149881' in t.manager_id) > 0 ; SELECT t.* from bas_cm_customer t where strpos(t.manager_id, '6651545956882725395' ) > 0 or strpos(t.manager_id, '5722501350582149881' ) > 0; SELECT t.* from bas_cm_customer t where '6651545956882725395' ~ t.manager_id or '5722501350582149881' ~ t.manager_id; SELECT t.* FROM bas_cm_customer t WHERE (string_to_array( '6651545956882725395,5722501350582149881' , ',' ) && string_to_array(t.manager_id, ',' )) |
此处不比较这几种写法的性能问题,前四种写法,如果后端语言是Java的话,使用的ibatis或者mybatis,那示例如下:
Java部分:
1
2
3
4
|
if (StringUtils.isNotEmpty(managerId)){ String[] managerIds = managerId.split( "," ); queryParam.put( "managerIds" , managerIds); } |
ibatis和mybatis差不多,要改下标签:
1
2
3
4
5
|
<isNotEmpty prepend= "and" property= "managerIds" > <iterate property= "managerIds" conjunction= "OR" > position(#managerIds[]# in bc.manager_id) > 0 </iterate> </isNotEmpty> |
这里演示了 position函数的用法,strpos和~写法与position写法大致相同,就不贴出代码了。
相较于前四种写法,第五种写法,Java只要传来字符串即可,Java层不需要做处理,直接把字符串传来即可。
补充:pgsql 判断逗号分割字符串是否包含的方式
我就废话不多说啦,大家还是直接看代码吧~
1
2
3
4
|
SELECT ARRAY[1] <@ string_to_array('1,2,3,4,5,6', ',')::int[]; SELECT position(1::VARCHAR in '1,2,3,4,5,6'); SELECT strpos(1::VARCHAR,'1,2,3,4,5,6'); SELECT '1,2,3,4,5,6' ~ 1::VARCHAR; |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/cainiaobulan/article/details/88830929