[英]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 更好的解决方案是使用union all
,因此服务器不会检查不同的值
select name, phone, 'users' as table_name from users
union all
select name, phone, 'vendors' as table_name from vendors;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.