Mysql 我可以在同一个查询中计算两个不同的事物吗?

Mysql 我可以在同一个查询中计算两个不同的事物吗?,mysql,sql,count,Mysql,Sql,Count,我有一张这样的桌子: // question_and_answers +----+---------+---------------+--------+------+ | id | title | body | amount | type | +----+---------+---------------+--------+------+ | 1 | t1 | b1 | NULL | 0 | | 2 | t2 | b2

我有一张这样的桌子:

// question_and_answers
+----+---------+---------------+--------+------+
| id |  title  |      body     | amount | type |
+----+---------+---------------+--------+------+
| 1  | t1      | b1            | NULL   | 0    |
| 2  | t2      | b2            | NULL   | 1    |
| 3  | t3      | b3            | NULL   | 1    |
| 4  | t4      | b4            | 100    | 0    |
| 5  | t5      | b5            | NULL   | 0    |
| 6  | t6      | b6            | NULL   | 1    |
| 7  | t7      | b7            | 50     | 0    |
+----+---------+---------------+--------+------+
我有两个问题:

1:问题数量: 2:付费问题的数量:
我可以合并这两个查询吗?我的意思是我可以写一个查询来代替它们吗?

您可以使用条件聚合:

SELECT sum(type = 0 AND amount IS NOT NULL),
       count(*) 
FROM question_and_answers 
WHERE type = 0
在MySQL中,比较的结果是0或1。您可以像上面的查询一样对这些结果进行汇总

要使其适用于其他DB引擎,您可以使用以下常规ANSI SQL方法:

SELECT sum(case when type = 0 AND amount IS NOT NULL then 1 else 0 end),
       count(*)
FROM question_and_answers 
WHERE type = 0
或计数:


您可以使用以下查询:

select count(1) as count1  , sum(if(amount is not null,1,0)) as count2 from question_and_answers where type=0
类型为0的计数的计数1, 类型为0且金额不为空的计数的计数2。
如果您使用sql server,请在查询中使用IIF而不是If。

谢谢,upvote。为什么要求和?为什么不算数?因为我只想计算行数,而不是聚合一些东西。我想在type=0的地方添加一个条件。它不会改变结果,但可以提高性能。您也可以使用count,但count会对所有非空值进行计数,无论它们是什么。因此,当type=0时,必须使用类似sumcase的东西,然后使用1,否则为null endyes。。添加诸如where type=0这样的条件将使其速度更快。因为我有一个关于类型列的索引,老实说,我不明白。。where子句的条件类型为0。那么,为什么要在聚合函数中再次使用它呢?换句话说,您的第一个查询和第二个查询之间有什么不同吗?
SELECT sum(case when type = 0 AND amount IS NOT NULL then 1 else 0 end),
       count(*)
FROM question_and_answers 
WHERE type = 0
SELECT count(case when type = 0 AND amount IS NOT NULL then 1 else null end),
       count(*) 
FROM question_and_answers 
WHERE type = 0
select count(1) as count1  , sum(if(amount is not null,1,0)) as count2 from question_and_answers where type=0