문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top