9

如果我有一个简单的工会

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

1 回答 1

26
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;
于 2012-10-20T20:20:49.400 回答