选择UNION ALL以将表名显示为附加列

时间:2015-01-15 15:57:20

标签: mysql sql select union

对于MSSQL或MySQL,这是一个将两个结果合二为一的查询:

SELECT boy as person from table1
union all
SELECT girl as person from table2

如何修改上面的查询,以便结果包含带有表名称的第二个(已添加)列(因此它包含table1table2值。)

3 个答案:

答案 0 :(得分:4)

你可以给表格名称作为第二栏的字​​符串横向

SELECT boy as person, 'table1' as column2 from table1
union all
SELECT girl as person, 'table2' as column2 from table2

答案 1 :(得分:3)

只需Hard code第二栏中的tablename

SELECT boy as person,'Table1' as Tablename from table1
UNION ALL
SELECT girl as person ,'Table2' as Tablename from table2

答案 2 :(得分:1)

您需要将它们添加为文字:

SELECT boy as person, 'table1' as tablename from table1
UNION ALL
SELECT girl as person, 'table2' from table2