有没有办法只获取我的字符串模式匹配的特定字段?

时间:2015-03-12 12:35:03

标签: mysql regex

SELECT (match cloumn only) from mytable WHERE col1 like '%ind%' or col2 '%ind%' or col3 '%ind%';

这应该只返回与不同列值匹配的字符串(不是整个记录)

Ex col1   col2   col3
   india  hello  world
   hello  linda  world
   hello  world  melinda

它应该只返回匹配的字符串,而不是整个记录

output:
india
linda
melinda

1 个答案:

答案 0 :(得分:1)

您可以使用case返回每行中第一个匹配列:

SELECT (case when col1 like '%ind%' then col1
             when col2 like '%ind%' then col2
             when col3 like '%ind%' then col3
        end)
from mytable
WHERE col1 like '%ind%' or col2 '%ind%' or col3 '%ind%';

如果您想要所有值,请改用union all

select col1 from mytable where col1 like '%ind%' union all
select col2 from mytable where col2 like '%ind%' union all
select col3 from mytable where col3 like '%ind%';