【问题标题】:how to do like query in MySQL find second word in string如何在MySQL中进行like查询在字符串中查找第二个单词
【发布时间】:2014-04-25 13:01:26
【问题描述】:

我想像通配符查询一样按第二个词搜索

这里有几列数据

sea food
food restaurant
Chinese food

如果我搜索“foo”。它应该返回

sea food
Chinese food

我如何在 MySQL 中做到这一点

【问题讨论】:

  • 所以它总是在字符串中的 2 个单词,即中餐、海鲜等?
  • 可以是单字也可以是多字。我想在他们的搜索中像 truelocal.com.au 那样做
  • 为什么不用像where food_name like '%foo%'这样的通配符
  • 它不起作用。它还返回食品餐厅。我想让第二个单词以查询开头

标签: mysql regex wildcard sql-like


【解决方案1】:

怎么样:-

select * from table where food_name like '% foo%'

【讨论】:

    【解决方案2】:

    在你的 sql 查询中使用正则表达式 .. 类似

    select * from table where col regexp '^[A-Za-z]+\s(foo).*$'
    

    编辑

    用过你的桌子..试试这个..

    select id,col from food where col regexp '^[A-Za-z]+ (foo)'
    

    【讨论】:

    • 它不返回任何行
    • 这里 sql 脚本如果不存在则创建表 food (id int(11) NOT NULL AUTO_INCREMENT, col varchar(100) NOT NULL, PRIMARY KEY (id)) ENGINE =InnoDB 默认字符集=latin1 AUTO_INCREMENT=4 ; INSERT INTO food (id, col) VALUES (1, '海鲜'), (2, '美食餐厅'), (3, '中餐');
    • 我使用您的 create table 语句更新了答案,现在应该可以正常工作了
    • 非常感谢,在那里我可以阅读有关 reg exp 的文档。我知道一点。像 \s 用于空格等
    • 不客气 Surjit,为了测试我的正则表达式,我使用 Antix Regex Tester found here .. antix.co.uk/Projects/Regex-Tester 这是正则表达式备忘单rexegg.com/regex-quickstart.html 希望对您有所帮助:)
    【解决方案3】:

    使用下面的查询。这将对您的情况有所帮助。

    select column-name-list from table-name 
    where right(your-desired-column-name,4) = 'food';
    

    【讨论】:

      【解决方案4】:

      这是一种方法

      select * from
      test
      where 
      substring_index(food_name,' ',-1) like '%foo%'
      AND 
      (
         LENGTH(food_name) - LENGTH( substring_index(food_name,' ',-1)) > 0
       )
      ;
      

      DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-23
        • 1970-01-01
        • 2015-12-05
        • 1970-01-01
        • 2013-04-08
        • 1970-01-01
        相关资源
        最近更新 更多