简体   繁体   English

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

[英]Select the table name as a column in a UNION select query in MySQL

I want to be able to select the name of a the table a row is from as a column in a union select query. 我希望能够选择行所在的表的名称作为联合选择查询中的列。 Something like this: 像这样的东西:

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

Does anyone know if this is possible? 有谁知道这是否可能? Thanks 谢谢

You are already querying on that table itself. 你已经在那张桌子上查询了。 Eg:- table1 and table2 例如: - table1和table2

So you can basically output table name as string itself - 所以你基本上可以输出表名作为字符串本身 -

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

given that you've got to type the table name into the sql anyway, why not just include it as a string in the select too? 鉴于你必须在sql中输入表名,为什么不把它作为字符串包含在select中呢? ie

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM