Add table name field for SQL results from UNION?

If I have a simple union

select name, phone from users union select name, phone from vendors; 

Is there a way to add a table name to the results?

So instead

 +--------+-------+ | name | phone | +--------+-------+ | Jim | 123...| | Macy | 345...| +--------+-------+ 

I would get

 +--------+-------+---------+ | name | phone | table | +--------+-------+---------+ | Jim | 123...| users | | Macy | 345...| vendors | +--------+-------+---------+ 
+4
source share
1 answer
 select name, phone, 'users' as table_name from users union select name, phone, 'vendors' as table_name from vendors; 

The best solution would be to use union all , so the server will not check individual values

 select name, phone, 'users' as table_name from users union all select name, phone, 'vendors' as table_name from vendors; 
+16
source

Source: https://habr.com/ru/post/1441008/


All Articles