小编典典

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

sql

如果我有一个简单的工会

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 |
+--------+-------+---------+

阅读 206

收藏
2021-03-23

共1个答案

小编典典

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;
2021-03-23