【问题标题】:Mysql REGEXP return results and matched valuesMysql REGEXP 返回结果和匹配值
【发布时间】:2014-01-14 15:37:32
【问题描述】:

我需要在mysql中进行搜索:

SELECT * 
 FROM table 
 WHERE data REGEXP 'firstValue|secondValue|thirdValue'

我需要的是检索匹配例如firstValue的行,并在查询结果中返回这些行和匹配的词,例如:

id     -     data                        - matched_term
 1     -  blabla firstValue              -  firstValue
 2     -  blabla secondValue blabla      -  secondValue

【问题讨论】:

    标签: mysql regex match


    【解决方案1】:

    好吧,你可以这样做:

    SELECT t.*,
           (case when data regexp 'firstvalue' then 'firstValue'
                 when data regexp 'secondValue' then 'secondValue'
                 when data regexp 'thirdValue' then 'thirdValue'
            end) as which
    FROM table t
    WHERE data REGEXP 'firstValue|secondValue|thirdValue';
    

    如果您只是在进行持续比较(意味着 data 完全匹配其中一个值),那么我会建议使用不同的函数:

    SELECT t.*,
           (case when data = 'firstvalue' then 'firstValue'
                 when data = 'secondValue' then 'secondValue'
                 when data = 'thirdValue' then 'thirdValue'
            end) as which
    FROM table t
    WHERE data in (firstValue, secondValue, thirdValue')
    

    【讨论】:

    • 它可以在少数匹配的情况下使用,但它们可能是数千个,我的意思是“第一|第二|第三|第四|...千”
    猜你喜欢
    • 2015-10-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多