在MySQL中的UNION选择查询中选择表名作为列

时间:2010-11-24 11:19:24

标签: mysql union

我希望能够选择行所在的表的名称作为联合选择查询中的列。像这样:

SELECT [TABLENAME], text from table1
UNION
SELECT [TABLENAME], text from table2
ORDER BY date

有人知道这是否可行? 感谢

2 个答案:

答案 0 :(得分:9)

你已经在那张桌子上查询了。例如: - table1和table2

所以你基本上可以将表名输出为字符串本身 -

SELECT 'table1' as tableName, text from table1
UNION
SELECT 'table2' as tableName, text from table2
ORDER BY date

答案 1 :(得分:0)

鉴于你必须在sql中输入表名,为什么不将它作为字符串包含在select中呢?即。

SELECT 'table1' as tablename, text from table1
UNION
SELECT 'table2' as tablename, text from table2
ORDER BY date
相关问题