如何用UNION结果选择表名?

时间:2016-04-23 19:31:02

标签: php mysql

以下是UNION的结果,但我也想知道与每行关联的源表:

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

查询的实际结果如下:

  

城市
  572个
  123

但我反而喜欢这个结果:

  

city tablet_result
  572客户
  123供应商

2 个答案:

答案 0 :(得分:2)

SELECT City, 'Customers' as tablet_result FROM Customers
UNION
SELECT City, 'Suppliers' as tablet_result FROM Suppliers

答案 1 :(得分:2)

好的,试试:

SELECT City,'Customers' as tblName FROM Customers
UNION
SELECT City,'Suppliers' as tblName FROM Suppliers
ORDER BY City;

按照订单玩。

还要考虑做一个UNION ALL。有关差异,请参阅this