【问题标题】:MySQL : How to know which table that record belongs to in UNION resultMySQL:如何知道该记录在 UNION 结果中属于哪个表
【发布时间】:2013-09-04 06:53:41
【问题描述】:
假设我想使用 UNION 从 2 个表中获取记录。
如何向每条记录添加一个字段来告诉我它属于哪个表?就是这样:
id | title | link | table
-----------------------------------------------------
1 | Title 1 | somelink.html | articles1
2 | Title 2 | link2 .html | articles2
3 | Title 3 | link3 .html | articles1
提前致谢?
【问题讨论】:
标签:
mysql
field
union
record
belongs-to
【解决方案1】:
select some_column, 'union_1' as from_where
from table1
union
select some_column, 'union_2' as from_where
from table2
【解决方案2】:
你可以试试
SELECT Col1, Col2, 'Table1' TableSource
FROm Table1
UNION ALL
SELECT Col1, Col2, 'Table2' TableSource
FROm Table2
这对UNION ALL 有效/有意义,但如果您使用UNION,则可能会产生误导,因为由于源列不同,因此将包含重复项。
【解决方案3】:
只要把它放在你的 UNION 中,比如:
SELECT *, 'articles1' AS table_name FROM articles1
UNION ALL
SELECT *, 'articles2' AS table_name FROM articles2