获取与多列搜索匹配的列名称

时间:2016-11-07 09:20:05

标签: sql-server tsql

对于应用程序,我需要根据多个列显示搜索结果。在多列中搜索不是hard,但我还想知道搜索查询与文本匹配的列。

想象一下'Blabla'表:

---------------------------------------------------------------------------------------
| column1                |  column2                  | column 3                       |
---------------------------------------------------------------------------------------
| Animals are beautiful  | Some text regarding music | Vague statement about politics |
---------------------------------------------------------------------------------------
| Music is not his thing | Green is a color          | Random gibberish about music   |
--------------------------------------------------------------------------------------- 

搜索“音乐”这个词就像这样简单:

SELECT * FROM Blabla WHERE column1 LIKE '%music%' OR column2 LIKE '%music%' OR column2 LIKE '%music%';

但在SQL中是否有一种方法可以显示第1行的匹配列为column2,第2行为column1 + column3

4 个答案:

答案 0 :(得分:1)

您可以使用CASE声明:

SELECT CASE WHEN column1 LIKE '%music%' THEN 'Column1' ELSE '' END AS col1match,
       CASE WHEN column2 LIKE '%music%' THEN 'Column2' ELSE '' END AS col2match,
       CASE WHEN column3 LIKE '%music%' THEN 'Column3' ELSE '' END AS col3match
FROM Blabla

答案 1 :(得分:1)

那将是

select
  column1,
  column2, 
  column3,
  case
    when column1 like '%music%' then 'column1'
    when column2 like '%music%' then 'column2'
    when column3 like '%music%' then 'column3'
    else ''
  end as [column]
from Blabla where column1 like '%music%' or column2 like '%music%' or column3 like '%music%'

不确定这实际上是多么高效。

答案 2 :(得分:1)

是的,您可以将CASE EXPRESSION用于指示列:

SELECT s.* FROM (
    SELECT t.*,
           CASE WHEN t.column1 LIKE '%music%' THEN 1 ELSE 0 as col_1_ind,
           CASE WHEN t.column2 LIKE '%music%' THEN 1 ELSE 0 as col_2_ind,
           CASE WHEN t.column3 LIKE '%music%' THEN 1 ELSE 0 as col_3_ind
    FROM Blabla t) s
WHERE 1 IN(s.col_1_ind,s.col_2_ind,s.col_3_ind)

答案 3 :(得分:0)

试试这个,

declare @t table(column1 varchar(100), column2 varchar(100),column3 varchar(100))
insert into @t values
('Animals are beautiful','Some text regarding music','Vague statement about politics')

,('Music is not his thing','Green is a color','Random gibberish about music')

;With CTE as
(
 select column1,column2,column3,ROW_NUMBER()over(order by (select null))rn from @t
)
select case when column1 LIKE '%music%' then 'column1 in row'+ cast(rn as varchar) end
,case when column2 LIKE '%music%' then 'column2 in row'+ cast(rn as varchar) end
,case when column3 LIKE '%music%' then 'column3 in row'+ cast(rn as varchar)
end
from cte