如何使用UNION获得两个独立的选择器?

时间:2015-09-15 17:01:31

标签: mysql sql

遗憾的是SQL是我最弱的技能。

我尝试在UNION中使用VIEW,我可以通过一个查询从两个不同的表中获取统计信息。

SELECT COUNT(*) AS `customer_count` FROM `Customers`
UNION
SELECT COUNT(*) AS `supplier_count` FROM `Suppliers`;

[Demo table]

但是,它只返回两行 customer_count 。无论如何,要做到这一点,它会分别返回 customer_count supplier_count 吗?

4 个答案:

答案 0 :(得分:1)

select
(SELECT COUNT(*) FROM Customers) as customer_count,
(SELECT COUNT(*) FROM Suppliers) AS supplier_count

答案 1 :(得分:1)

使用您的表格演示。

密钥是使用别名,因此字段名称在每个联合选择上匹配。

在这种情况下TableSourceTotal

SELECT 'Customer' as TableSource, Count(City) as Total FROM Customers
UNION
SELECT 'Suppliers' as TableSource, Count(City) as Total FROM Suppliers;

答案 2 :(得分:1)

您需要cross join才能在一行中看到彼此相邻的结果。因此,如果没有select条件,您可以join。{/ p>

select * from
(select count(*) as customer_count from Customers) x,
(select count(*) as supplier_count from Suppliers) y

答案 3 :(得分:0)

CREATE  VIEW `vw_count` AS 
select (select count(0) from `tbl`) AS   `customer_count`,
       (select count(0) from `tbl2`) AS `supplier_count`;