我正在尝试连接两个计数查询
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
最佳答案
您不需要 UNION
查询来执行此操作。 SELECT A UNION SELECT B
返回 A
的行,后跟 B
的行(去重;如果您想要来自两个数据集的 all 行,请使用 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
表达式,如果 status='6'
则返回 1
:
select
count(*) from clients,
sum(case when status='6' then 1 else 0 end) as converts
from clients
关于mysql - SQL 联合查询错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25394783/