简体   繁体   中英

Add “field” of table name to 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 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 |
+--------+-------+---------+
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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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