如何模糊匹配多行数据

场景大致是这样,示例:
现有一个子查询1,查询出两个数据:
苹果
桃子

在查询2(将子查询1包裹其中),按照子查询1的结果进行模糊匹配,得:
AAA苹果AAA
BBB苹果BBB
CCC桃子CCC
DDD桃子DDD

之前,子查询1只有一个数据的话,可以用like,但是like不支持2个以上的数据。
请教各位大佬,像此类问题该怎么处理。

select col1 from t1;

苹果

桃子

select col1 from t2;

AAA苹果AAA

BBB苹果BBB

CCC桃子CCC

DDD桃子DDD

-- 当 t1 表里的值没有重复

select t2.col1 from t2,t1 where t2.col1 like concat('%',t1.col1,'%');

-- 当 t1 表里的值有重复

select t2.col1 from t2,(select distinct col1 from t1)t1 where t2.col1 like concat('%',t1.col1,'%');

PS: like 左右百分号走不上索引的,业务上尽量不要这么设计

两个表关联用 like 条件,会产生笛卡尔积,也不好

1 个赞

select * from (
select ‘AAA苹果AAA’ as c1 union all
select ‘BBB苹果BBB’ as c1 union all
select ‘CCC桃子CCC’ as c1 union all
select ‘DDD桃子DDD’ as c1 union all
select ‘EEE梨EEE’ as c1
) t2 where exists(
select * from (
select ‘苹果’ as c1 union all
select ‘桃子’ as c1
) t1 where t2.c1 like concat(‘%’,t1.c1,‘%’)
)

如果都是 AAA**AAA,格式,不要用like,直接截断,然后等值join

具体看数据,用正则表达式

使用 REGEXP 与 GROUP_CONCAT

WITH t1 AS (
select 'AAA苹果AAA' as c1 union all
select 'BBB苹果BBB' as c1 union all
select 'CCC桃子CCC' as c1 union all
select 'DDD桃子DDD' as c1 union all
select 'EEE梨EEE' as c1
),
t2 AS (
select '苹果' as c1 union all
select '桃子' as c1
)

SELECT *
FROM t1
WHERE t1.c1 REGEXP(
  SELECT GROUP_CONCAT(t2.c1 SEPRARTOR "|")
  FROM t2
)
1 个赞

我什么时候也能写出这样的SQL就好了。

不错不错

此话题已在最后回复的 7 天后被自动关闭。不再允许新回复。