简体   繁体   English

Mysql REGEXP返回结果和匹配值

[英]Mysql REGEXP return results and matched values

I need to do a search in mysql: 我需要在mysql中进行搜索:

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

What i need is to retrieve the the rows matching for example firstValue, and return these rows and the matched term in the result of the query, for example: 我需要的是检索匹配例如firstValue的行,并在查询结果中返回这些行和匹配的术语,例如:

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

Well, you can do: 好吧,你可以这样做:

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';

If you are doing just constant comparisons (meaning that data exactly matches exactly one of the values), then I would suggest different functions: 如果您只是进行固定比较(意味着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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM