MySQL:在一个查询中计数两件事情? [英] MySQL: Count two things in one query?

查看:88
本文介绍了MySQL:在一个查询中计数两件事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在其中一个表格中有一个boolean列(值为0或1)。

I have a "boolean" column in one of my tables (value is either 0 or 1).

我需要得到两个计数:布尔值设置为0,行数设置为1.目前我有两个查询:一个计数1,另一个计数0。

I need to get two counts: The number of rows that have the boolean set to 0 and the number of rows that have it set to 1. Currently I have two queries: One to count the 1's and the other to count the 0's.

当使用WHERE条件计算行时,MySQL是否遍历整个表?我想知道是否有一个查询,将允许两个计数器基于不同的条件?

Is MySQL traversing the entire table when counting rows with a WHERE condition? I'm wondering if there's a single query that would allow two counters based on different conditions?

还是有办法获得总计数与WHERE条件数?这就足够了,因为我只需要从一个计数减去另一个(由于列的布尔性质)。没有NULL值。

Or is there a way to get the total count along side the WHERE conditioned count? This would be enough as I'd only have to subtract one count from the other (due to the boolean nature of the column). There are no NULL values.

感谢。

推荐答案

 SELECT bool_column, COUNT(bool_column) FROM your_table
 WHERE your_conditions
 GROUP BY bool_column

这显然不仅适用于bool列,与其他数据类型,如果你需要。

This will obviously work not only for bool columns but also with other data types if you need that.

这篇关于MySQL:在一个查询中计数两件事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆