php MySQL发现多个示例LIKE '%pp%'和LIKE '%p%'不匹配“hippo”

pvabu6sv  于 2023-06-28  发布在  PHP
关注(0)|答案(2)|浏览(121)

我试图匹配关键字使用多个LIKE的,但我希望能够这样做:

SELECT * FROM `keywords` WHERE keyword LIKE '%pp%' AND keyword LIKE '%p%';

匹配“hippopotamus”而不是“hippo”
我明白我可以简单地做到:

SELECT * FROM `keywords` WHERE keyword LIKE '%pp%p%';

不过,我想知道是否有其他方法我可以采取。上面的例子很好,但对于其他例子,我有几个OR,如:

LIKE '%pp%p%' OR LIKE '%p%pp%' OR LIKE '%pp%p%pp%

等等,而且会变得非常混乱。
有谁知道更漂亮的方法吗?

xzlaal3s

xzlaal3s1#

这可以通过REGEXP来实现,如下所示:

SELECT * FROM `keywords` WHERE keyword REGEXP '([^p]|^)p([^p]|$)' AND keyword LIKE '%pp%';

测试和解释:(MySQL Workbench 8.0 CE)

drop table if exists keywords;
create table keywords(
keyword varchar(50)
);
insert into keywords values("hippo");
insert into keywords values("hippopotamus");
insert into keywords values("zpp");
insert into keywords values("zp");
insert into keywords values("zpzpp");
insert into keywords values("zppzp");
insert into keywords values("zppzpzzzzzppzppzp");
insert into keywords values("p");
insert into keywords values("pp");
SELECT * FROM `keywords` WHERE keyword REGEXP '([^p]|^)p([^p]|$)'; -- Returns words with 'p' that isn't 'pp'
SELECT * FROM `keywords` WHERE keyword LIKE '%pp%'; -- Returns words with 'pp'
SELECT * FROM `keywords` WHERE keyword REGEXP '([^p]|^)p([^p]|$)' AND keyword LIKE '%pp%'; -- Combine to get desired effect
-- Should only get 'hippopotamus' 'zpzpp' 'zppzp' and 'zppzpzzzzzppzppzp'
r7xajy2e

r7xajy2e2#

我建议在这里使用MySQL REGEXP,smth像这样:

WHERE keyword REGEXP '(?=^.*?[^p](p)[^p].*?$)(?=^.*?[^p](p{2})[^p].*?$)'

我还没有测试过,但只有当ppp以任何顺序同时出现时,它才应该为真

相关问题