【问题标题】:Having some troubles finding a string for in MySQL在 MySQL 中查找字符串时遇到一些麻烦
【发布时间】:2016-04-05 14:56:13
【问题描述】:

我正在一个 MySQL 数据库中做一些研究,其中一些数据存储为 XML。我已经设法找到我正在搜索的字符串:

select * from foo where Concat(foo) like '%bar%';

现在我试图只查找“栏”出现 2 次的条目。在我搜索“bar”的表格中总是出现一次,所以我想找到至少有 2x 个“bar”的条目。

你能给我一些建议吗?

【问题讨论】:

    标签: mysql sql regex xml


    【解决方案1】:

    你应该使用REGEXP方法

    select * from foo where Concat(foo) regexp '(bar).*(bar)';
    

    故障

    ()- 第一个捕获组

    bar - 要捕获的表达式

    . - 匹配任何字符

    * - 匹配零个或多个字符

    (bar) - 第二个捕获组

    https://regex101.com/r/wM3wX9/1

    来自 MySQL 文档

    对模式 pat 执行字符串表达式 expr 的模式匹配。该模式可以是扩展的正则表达式,其语法将在本节后面讨论。如果 expr 匹配 pat,则返回 1;否则返回 0。如果 expr 或 pat 为 NULL,则结果为 NULL。 RLIKE 是 REGEXP 的同义词,提供 mSQL 兼容性。

    我还为此创建了一个 SQL Fiddle。

    http://sqlfiddle.com/#!9/49fd7/1/0

    【讨论】:

      【解决方案2】:

      这里有一个scalable的解决方案,可以很方便的用在任意重复次数上,比如1、2、10、100等。

      -- match twice
      select * from foo where (length(foo) - replace(foo,'bar',''))/length('bar') = 2;
      
      -- match 3 repeated times
      select * from foo where (length(foo) - replace(foo,'bar',''))/length('bar') = 3;
      
      -- match 100 repeated times
      select * from foo where (length(foo) - replace(foo,'bar',''))/length('bar') = 100;
      

      参考:

      SQL function to get count of how many times string appears in column?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-19
        • 1970-01-01
        • 1970-01-01
        • 2013-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        相关资源
        最近更新 更多