在UNION的SQL结果中添加表名称的“收成”?

问题描述

select name, phone, 'users' as table_name from users
union
select name, phone, 'vendors' as table_name from vendors;

更好的解决方案是使用union all,因此服务器将不会检查不同的值

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

解决方法

如果我有一个简单的工会

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

有没有一种方法可以将表名添加到结果中?

所以代替

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

我会

+--------+-------+---------+
| name   | phone | table   |
+--------+-------+---------+
| Jim    | 123...| users   |
| Macy's | 345...| vendors |
+--------+-------+---------+