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) 

1 Answer

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy