【问题标题】:How to make the column wildcard based on the entry?如何根据条目制作列通配符?
【发布时间】:2022-01-21 10:39:24
【问题描述】:

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

请看这个:

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

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

【问题讨论】:

    标签: mysql sql where-clause


    【解决方案1】:

    您将通配符 % 粘贴到 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)
              )
    

    dbfiddle here

    上的演示

    【讨论】:

    • 真的吗?那可能吗?谢谢
    • 是否有任何方法可以使用 MySQL 根据空间将单词分开?
    • 您的意思是类似于 MS Sql Server 中的 STRING_SPLIT 将字符分隔的字符串拆分为行?那么不,据我所知,MySql 没有这样的东西。 MySql 函数不能返回表,只有过程可以。但是一些复杂的技巧可能会奏效。 F.e. here
    • 好吧,我需要根据“John Foo”字符串以某种方式制作IN ('John','Foo'),以利用索引(如你所述)
    • 见补充。它假设一个名称不超过 3 个部分。
    【解决方案2】:

    您也许可以使用LOCATE()

    选择 * FROM tb_name WHERE LOCATE(name, 'John Foo') > 0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 2015-10-01
      • 2023-03-05
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 2015-08-15
      相关资源
      最近更新 更多