简体   繁体   中英

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).

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. Then for each result column add another column wrapped in isNull() to indicate what column it came from.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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