如何根据条目制作列通配符?

How to make the column wildcard based on the entry?

如您所知,如果您使用.. where col_name like "%word%",那么它将作为通配符进行搜索。好的,一切都是文件。现在我想要恰恰相反。我的意思是,我想根据条目制作列通配符。

请看这个:

// tb_name
+--------------+
|   col_name   |
+--------------+
| Ali          |
| Martin       |
| John         |
+--------------+

我想通过这个值匹配第三行:John Foo。或通过此条目匹配第一行:Mr Ali。所以从概念上讲,我想要这样的东西:.. where %col_name% like "word"。我怎样才能在 MySQL 中做到这一点?

您或许可以使用 LOCATE()

SELECT * 来自 tb_name 位置(名称,'John Foo')> 0

您将通配符 % 设置为 col_name。

那你就给John Foo点个赞吧

select *
from tb_name 
where 'John Foo' like concat('%',col_name,'%') 

但是如果col_name被索引,那么使用IN会更快。
因为 concat('%',col_name,'%') 不是 sargable.

select *
from tb_name 
where col_name IN ('John','Foo') 

或者更复杂的方法,从名称字符串中获取部分。

select t.*
from tb_name t
cross join (select 'John Foo Bar' name) names
where t.col_name IN (
           substring_index(name,' ',1), 
           substring_index(substring_index(name,' ', 2),' ',-1), 
           substring_index(substring_index(name,' ', 3),' ',-1)
          )

演示 db<>fiddle here