用REGEXP语句实现判断两个字符串组合之间是否有交集

之前做了一个呼叫功能,呼叫项目和人员之间通过标签关联。比如呼叫项目关联a标签,b标签,人员关联b标签,c标签。方式是通过一个字段保存了用逗号分割的标签id。只要他们关联了同一个标签,到时候呼叫就通知到那个人员。不过后来需求改了要直接把呼叫关联到人员。这个时候我就需要修改的过去数据,把呼叫的id直接关联到人员。

如果用java写代码的话这是很简单的,不过我想用语句实现,查找资料后判断两个字符串组合是否有交集大部分是通过定义一个函数来实现的,但是我用的tidb数据库并不能定义函数。

我只能使用like方法

insert into call_label_user(userId,companyId,label)
select clu.userId,clu.companyId,c.id label
-- 呼叫表
from call c
-- 呼叫人员表
join call_label_user clu on (clu.label like concat('%',c.label,'%')
or c.label like concat('%',clu.label,'%')) and clu.label != '' and c.label != ''
and clu.companyId = c.companyId
-- 判断表格中是否已经存在呼叫人员关联关系,避免多次执行插入重复数据
left join call_label_user clu2 on clu.userId = clu2.userId and clu.companyId = clu2.companyId and c.id = clu2.label
where clu2.id is null

这个办法只查询出了呼叫和人员分别关联了单个标签的情况。

很明显还漏掉了一些情况,于是我又继续查找资料,这时候我发现了一个神奇的关键词regexp。

insert into call_label_user(userId,companyId,label)
select clu.userId,clu.companyId,c.id label
-- 呼叫表
from call c
-- 呼叫人员表
join call_label_user clu on (clu.label regexp replace(c.label,',','|')
or c.label regexp replace(clu.label,',','|')) and clu.label != '' and c.label != ''
and clu.companyId = c.companyId
-- 判断表格中是否已经存在呼叫人员关联关系,避免多次执行插入重复数据
left join call_label_user clu2 on clu.userId = clu2.userId and clu.companyId = clu2.companyId and c.id = clu2.label
where clu2.id is null

通过把,号替换成|就能用正则来判断,两边交叉对比判断就能获得所有符合的情况。

我的问题实际上解决了,不过深入思考后我发现这是因为我保存的标签id是uuid,不存在重复的情况,如果是名称或者id是数字那么这个判断是不严谨的。

比如两个字符串组合"123,321,456"和"23,32",如果用上述方法是不行的。我决定对其进行优化。

思路是除了正则前面要么是逗号要么是开头,后面要么是逗号要么是结尾,经过尝试后是可行的

select '123,321,456' regexp '23|32';//结果是1
select '123,321,456' regexp '(^|,)(23|32)($|,)';//结果是0
select '123,321,456' regexp '(^|,)(123|32)($|,)';//结果是1
select '123,321,456' regexp '(^|,)(23|321)($|,)';//结果是1

那么上面的语句可以继续优化(虽然没有必要)

insert into call_label_user(userId,companyId,label)
select clu.userId,clu.companyId,c.id label
-- 呼叫表
from call c
-- 呼叫人员表
join call_label_user clu 
on (clu.label regexp concat('(^|,)(',replace(c.label,',','|'),')($|,)')
or c.label regexp concat('(^|,)(',replace(clu.label,',','|'),')($|,)')) 
and clu.label != '' and c.label != ''
and clu.companyId = c.companyId
-- 判断表格中是否已经存在呼叫人员关联关系,避免多次执行插入重复数据
left join call_label_user clu2 on clu.userId = clu2.userId and clu.companyId = clu2.companyId and c.id = clu2.label
where clu2.id is null

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章