最近有需要用到求两个字符串是否有交集(原本想要求相似度的,暂时无法实现,只好转为判断是否存在交集的替代方案)方法,暂时找到以下2个方法。
方法一:正则
select concat(str1, ',') regexp concat(replace(str2,',',',|'),',');
示例:
select '123|456|125' regexp '123|126';
select '123' regexp '123|456';
select concat('123,456', ',') regexp concat(replace('456,789',',',',|'),',');
select concat('123,456', ',') regexp concat(replace('456,',',',',|'),',');
select concat('电子信息,科技', ',') regexp concat(replace('软件工程,电子信息,概率统计',',',',|'),',');
select concat(',', ',') regexp concat(replace('软件工程,电子信息,概率统计',',',',|'),',');
方法二:
DROP FUNCTION IF EXISTS `INTE_ARRAY`;
CREATE DEFINER=`root`@`localhost` FUNCTION `INTE_ARRAY` (setA varchar(255),setB varchar(255)) RETURNS int(1)
DETERMINISTIC
BEGIN
DECLARE idx INT DEFAULT 0 ;
DECLARE len INT DEFAULT 0;
DECLARE llen INT DEFAULT 0;
DECLARE clen INT DEFAULT 0;
DECLARE tmpStr varchar(255);
DECLARE curt varchar(255);
SET len = LENGTH(setB);
WHILE idx < len DO
SET idx = idx + 1;
SET tmpStr = SUBSTRING_INDEX(setB,",",idx);
SET clen = LENGTH(tmpStr);
IF idx = 1 THEN SET curt = tmpStr;
ELSE SET curt = SUBSTRING(setB,llen+2,clen-llen-1);
END IF;
IF curt != '' and FIND_IN_SET(curt,setA) > 0 THEN RETURN 1;
END IF;
IF clen <= llen THEN RETURN 0;
END IF;
SET llen = clen;
END WHILE;
RETURN 0;
END;
测试:
select INTE_ARRAY("1,3,5,9","8,2,3,7") as is_inte_array;
select INTE_ARRAY("电子信息,科技","电子信息科技,软件工程") as is_inte_array;
select INTE_ARRAY("电子信息,科技","电子信息") as is_inte_array;
select INTE_ARRAY("电子信息,科技","电子信息,科技") as is_inte_array;
select INTE_ARRAY(",","电子信息,科技") as is_inte_array;
|