简体   繁体   English

如何在查询结果中返回列名?

[英]How do I return column names in my query results?

I am using this query: 我正在使用此查询:

Select *
From table1
Join table2 on
     table2.column1
     + table2.column2
     + table2.column3
     + table2.column4
LIKE '%'
     + table1.column1
     + '%'
ORDER BY table1.column1

How do I also return the column name where the result was found. 我还如何返回找到结​​果的列名称。 For example, if the word "bob" in table1.column1 is found in table2.column3 (call this column "comments"), then the query result should have "bob", followed by "comments" (t2.c3), followed by all other columns (t2.c1, t2.c2, t2.c3, t2.c4). 例如,如果在table2.column3中找到table1.column1中的单词“ bob”(将此列称为“ comments”),则查询结果应具有“ bob”,后跟“ comments”(t2.c3)其他所有列(t2.c1,t2.c2,t2.c3,t2.c4)。

Select x.bob, y.column1, y.column2, y.column3, y.column4
From table1 x
Join table2 y on
     table2.column1
     + table2.column2
     + table2.column3
     + table2.column4
LIKE '%'
     + table1.column1
     + '%'
ORDER BY table1.column1

I dont know what you are trying to do, but you can get 'columns' where data is found by this simple trick. 我不知道您要做什么,但是您可以通过这个简单的技巧在“列”中找到数据。 Modify as necessary. 根据需要进行修改。

Instead of doing select * , list out all your result columns. 而不是select * ,而是列出所有结果列。 Then for each result column add another column wrapped in isNull() to indicate what column it came from. 然后为每个结果列添加包裹在isNull()中的另一列,以指示它来自哪一列。

Select 

table2.comments,
isNull(table2.comments, null, 'comments') col1,

table2.column2,
isNull(table2.column2, null, 'column2') col1

From table1 
Join table 2 on 
     table2.column1 
     + table2.column2 
     + table2.column3 
     + table2.column4 
LIKE '%' 
     + table1.column1 
     + '%' 
ORDER BY table1.column1

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

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