mysql - SQL 联合查询错误

标签 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

最佳答案

您不需要 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/

相关文章:

mysql不等于不工作

mysql - 如何在我的 CodeIgniter 模型中使用 ON DUPLICATE KEY UPDATE?

php - 如何使用 joomla 2.5 中的外部文件访问登录用户数据?

mySQL,网站统计: unique daily visits

mysql - SELECT * 与 SELECT * LIMIT(性能)

mysql - 多个 ORDER BY(获取最新元素)MySQL

c# - 有没有办法让 Linq to Entities 将无法识别的方法/函数映射到 MySql 函数?

mySQL:编辑/保存 my.cnf 文件

java - 如何在 Java 中为 Oracle 数据库创建只读连接

sql - 使用 to_char 和日期在 postgres 中添加生成的列