如何单独计算匹配的行数?

时间:2017-08-14 11:02:05

标签: mysql sql

这是我的表结构:

-- qanda (stands for questions and answers)
+----+---------+-----------------------------------------------+--------------+-----------+------+
| id |  title  |                      content                  |  question_id |  user_id  | type |
+----+---------+-----------------------------------------------+--------------+-----------+------+
| 1  | title1  | this is a question                            | NULL         | 213423    | 0    |
| 2  | NULL    | this is an answer                             | 1            | 435344    | 1    |
| 3  | NULL    | this is another answer                        | 1            | 432435    | 1    |
| 4  | title2  | this is another question                      | NULL         | 124324    | 0    |
| 5  | NULL    | this is an answer for the second question     | 4            | 213423    | 1    |
| 6  | NULL    | this is another answer for the first question | 1            | 213423    | 1    |
+----+---------+-----------------------------------------------+--------------+-----------+------+

我想单独计算问题和答案的数量。我怎么能这样做?

此用户的预期结果::user_id = 213423

+--------+--------+
| q_num  | a_num  |
+--------+--------+
| 1      | 2      |
+--------+--------+

我可以分别通过两个查询来做到这一点:

SELECT count(*) q_num FROM qanda WHERE user_id = :user_id AND question_id IS NULL

SELECT count(*) a_num FROM qanda WHERE user_id = :user_id AND question_id IS NOT NULL

我可以在一个查询中执行此操作吗?

3 个答案:

答案 0 :(得分:3)

你可以这样做:

SELECT count(questionid) as q_num,
       sum(questionid is null) as a_num
FROM qanda
WHERE user_id = :user_id ;
带有列或表达式的

count()会计算非NULL值的数量 - 这正是您想要做的。 MySQL将布尔值视为数字上下文中的整数,其中1表示true,0表示false。

您也可以将其写为:

(count(*) - count(questionid)) as a_num

sum(case when questionid is null then 1 else 0 end) as a_num

编辑:

使用类型,您可以使用变体:

select sum(type = 0) as q_num, sum(type = 1) as a_num

答案 1 :(得分:1)

SELECT 
 SUM(question_id IS NULL) a_num,
 SUM(question_id IS NOT NULL) q_num 
 FROM qanda 
 WHERE user_id = :user_id

尝试以上查询。

如上面的查询中所述,我使用了question_id IS NULL,它将为true生成1,为false生成0,因此SUM(question_id IS NOT NULL)将生成确切的问题计数。

同样可以回答。

答案 2 :(得分:1)

使用带有SUM语句的CASE即可完成此操作。

SELECT SUM(CASE WHEN question_id IS NULL 
                THEN 1
                ELSE 0
           END) AS q_num,
       SUM(CASE WHEN question_id IS NOT NULL 
                THEN 1
                ELSE 0
           END) AS a_num 
FROM qanda
WHERE user_id = :user_id

输出(user_id = '213423'

q_num a_num
1     2

SQL小提琴:http://sqlfiddle.com/#!9/4923c/2/0