2014-01-14 43 views
0

我需要做MySQL中的搜索:Mysql的REGEXP返回结果和匹配的值

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

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

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

回答

0

嗯,你可以这样做:

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') 
+0

它可以起到如果比赛里只有少数,但他们可能是成千上万的,我的意思是“第一|第二|三|四| ...千” –