2

I am trying to get table name in query result. The query I am trying to do involves multiple table. This is why I am trying to get a column with result which will indicate from which table the data taken from. Here is the code I am using

(SELECT DISTINCT column_1 as keywords from table_1) 
UNION ALL
(SELECT DISTINCT column_2 as keywords from table_2)
Devil's Dream
  • 655
  • 3
  • 15
  • 38

1 Answers1

7

Use this:

SELECT DISTINCT column_1 AS keywords, 'table_1' AS tablename
FROM table_1
UNION ALL
SELECT DISTINCT column_2 AS keywords, 'table_2' AS tablename
FROM table_2

It adds one more column tablename to result set, which contains originating table name.

mvp
  • 111,019
  • 13
  • 122
  • 148