- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select the table name as a column in a UNION select query with MySQL?
You can use AS command for this. Let us first create a table −
mysql> create table DemoTable ( Name varchar(20) ); Query OK, 0 rows affected (0.56 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+------+ | Name | +------+ | John | +------+ 1 row in set (0.00 sec)
Here is the query to create the second table.
mysql> create table DemoTable2 ( Name varchar(20) ); Query OK, 0 rows affected (0.59 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable2 values('Bob'); Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+------+ | Name | +------+ | Bob | +------+ 1 row in set (0.00 sec)
Following is the query to select the table name as a column in a UNION select query in MySQL −
mysql> select 'DemoTable' as DemoTable,Name from DemoTable union select 'DemoTable2' as DemoTable2,Name from DemoTable2 ;
This will produce the following output −
+--------------+------+ | DemoTable | Name | +--------------+------+ | DemoTable | John | | DemoTable2 | Bob | +--------------+------+ 2 rows in set (0.00 sec)
Advertisements