Reputation: 10421
If I have a simple union
select name, phone from users union select name, phone from vendors;
Is there a way to add the table name to the results?
So instead of
+--------+-------+
| name | phone |
+--------+-------+
| Jim | 123...|
| Macy's | 345...|
+--------+-------+
I'd get
+--------+-------+---------+
| name | phone | table |
+--------+-------+---------+
| Jim | 123...| users |
| Macy's | 345...| vendors |
+--------+-------+---------+
Upvotes: 11
Views: 18346
Reputation: 117400
select name, phone, 'users' as table_name from users
union
select name, phone, 'vendors' as table_name from vendors;
Better solution will be to use union all
, so server will not be checking for distinct values
select name, phone, 'users' as table_name from users
union all
select name, phone, 'vendors' as table_name from vendors;
Upvotes: 31