我需要帮助编写查询(mySQL)到
现在,我可以单独进行,如下所示:
SELECT count(users)FROM t1 WHERE project = 3
SELECT count(users)FROM t1 WHERE project = 3 AND status =“disabled”
但是必须有一种简单的方法将两者结合在一个查询中......
答案 0 :(得分:2)
Select
Project,
Count(Users),
Sum(Case When Status = 'Disabled' Then 1 Else 0 End)
From
T1
Group By Project
答案 1 :(得分:2)
您可以使用UNION:
mysql> SELECT count(users) AS result FROM t1 WHERE project = 3 UNION
SELECT count(users) AS result FROM t1 WHERE project = 3 AND status = "disabled"
+--------+
| result |
+--------+
| 2 |
| 1 |
+--------+
其他解决方案是子查询:
mysql> SELECT (SELECT COUNT(ID) FROM t1 WHERE project = 3) AS total_users,
(SELECT COUNT(ID) FROM t1 WHERE project = 3 AND status = 'disabled') AS disabled_users;
+-------------+----------------+
| total_users | disabled_users |
+-------------+----------------+
| 2 | 0 |
+-------------+----------------+
无论如何,关于这些解决方案的真相是两个单独的查询就可以了。只有在非常大的系统上这才重要。当我们查看数据库性能时,这两个将比两个单独的查询慢。我们想要这样做的唯一原因是连接到数据库的开销。
答案 2 :(得分:1)
当我打字时,斯图已经给出了答案。基本上我的语法略有不同:
select count(users), sum(if(status='disabled',1,0))
from t1
where project = 3 ;
答案 3 :(得分:-1)
你可以做点什么
SELECT status, count(users) FROM t1 **group by status** WHERE project = 3
获取状态的结果集以及该状态中有多少记录的计数。将所有计数一起添加到总计中,记住已禁用计数的“已禁用”计数。
答案 4 :(得分:-1)
SELECT status, count(users) FROM t1 group by status WHERE project = 3 AND status = "disabled"