Select a table name as a column in a query to select UNION in MySQL

I want to be able to select the name of the table from which the row is a column in the connection selection request. Something like that:

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

Does anyone know if this is possible? Thanks

+4
source share
2 answers

You are already querying this table. For example: - table1 and table2

This way you can basically print the table name as the string itself -

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

given that you still need to enter the table name in sql, why not just include it as a string in select? i.e.

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

All Articles