select some_column, 'union_1' as from_where
from table1
union
select some_column, 'union_2' as from_where
from table2
MySQL : How to know which table that record belongs to in UNION result
-
27-06-2022 - |
题
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?
解决方案
其他提示
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
不隶属于 StackOverflow