Question

Lets say that I want to get the records from 2 table by using UNION. How could I add a field to each record that would tell me which table it belongs to? It just something like this :

id     |    title     | link            | table
-----------------------------------------------------
1      | Title 1      | somelink.html   | articles1
2      | Title 2      | link2   .html   | articles2
3      | Title 3      | link3   .html   | articles1

Thanks in advance?

Was it helpful?

Solution

select some_column, 'union_1' as from_where
from table1
union 
select some_column, 'union_2' as from_where
from table2

OTHER TIPS

You could try something like

SELECT Col1, Col2, 'Table1' TableSource
FROm Table1
UNION ALL
SELECT Col1, Col2, 'Table2' TableSource
FROm Table2

This will work/make sense for UNION ALL, but might be misleading if you use UNION, as duplicates will then be included due to the differentiating source column.

Just put it in your UNION, like:

SELECT *, 'articles1' AS table_name FROM articles1
UNION ALL
SELECT *, 'articles2' AS table_name FROM articles2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top