SQL Union查询错误

时间:2014-08-19 23:54:50

标签: mysql sql

我正在尝试加入两个计数查询

SELECT COUNT(*) AS total FROM clients WHERE addedby = 1
UNION
SELECT COUNT(*) AS converts FROM clients WHERE addedby = 1 AND status = '6'

返回的是

total
4
0

这是正确的数据,我期待的是这个

total     converts
  4           0

3 个答案:

答案 0 :(得分:3)

您不需要UNION个查询来执行此操作。 SELECT A UNION SELECT B返回A行,后跟B行(重复数据删除;如果您想要来自两个数据集的所有行),请使用UNION ALL

你想要的是这样的:

select 
    (select count(*) from clients where addedby=1) as total,
    (select count(*) from clients where addedby=1 and status='6') as converts

执行此操作的其他方法是使用case ... end表达式,如果1返回status='6'

select 
    count(*) from clients, 
    sum(case when status='6' then 1 else 0 end) as converts
from clients

答案 1 :(得分:2)

不需要UNION,一次性完成。

SELECT COUNT(*) as total,
       SUM(CASE status WHEN '6' THEN 1 ELSE 0 END) as converts
FROM clients;

答案 2 :(得分:0)

编写此查询的最简单方法是作为条件聚合:

select count(*) as total, sum(status = '6') as converts
from cleints
where addedby = 1;

MySQL将布尔值视为整数,1为真,0为假。您可以只计算值的总和以获得计数。