简体   繁体   English

如何显示一个表在不同列中的mysql计数结果?

[英]How to display mysql count results from one table in different columns?

I have got one table wit users. 我有一个表机智的用户。 I want to collect girls and boys and display count numbers of them. 我想收集男孩和女孩并显示他们的数量。 I do this: 我这样做:

SELECT COUNT(`is_male`) AS 'boys' FROM `users` WHERE `is_male` = 1 UNION (SELECT COUNT(`is_male`) AS 'girls' FROM `users` WHERE `is_male` = 0) 

But it shows results in one column 'boys', how I can display one row with 2 columns 'boys' and 'girls'? 但是它以单列“ boys”显示结果,我如何以两列“ boys”和“ girls”显示一行?

Just use conditional aggregation: 只需使用条件聚合:

SELECT SUM(is_male = 1) AS boys,
       SUM(is_male = 0) as girls
FROM users ;

Notes: 笔记:

  • MySQL treats boolean expressions as numbers in a numeric context, with "1" as true and "0" as false (which is why this works). MySQL在数字上下文中将布尔表达式视为数字,“ 1”为true,“ 0”为false(这就是为什么)。
  • Only use single quotes for column and date constants, not for column names. 仅对列和日期常量使用单引号,而不对列名称使用单引号。
  • There is no need to escape your column or table names. 无需转义您的列名或表名。 Queries with lots of back-ticks are harder to read. 带有大量反引号的查询更难阅读。

You can use a conditional sum 您可以使用条件和

SELECT SUM(is_male = 1) AS boys,
       SUM(is_male = 0) AS girls
FROM users

or count, but then the ELSE part has to be NULL since COUNT counts all non-null values 或计数,但是ELSE部分必须为NULL,因为COUNT计算所有非空值

SELECT count(case when is_male = 1 then 1 else null end) AS boys,
       count(case when is_male = 0 then 1 else null end) AS girls
FROM users

That's conditional aggregation : 这是条件聚合:

SELECT SUM(is_male) AS boys,
       SUM(is_male <> 1) AS girls
FROM users;

MySQL evaluates Boolean expressions as 1 and 0 , so no need for case expression or anything . MySQL计算布尔表达式为1和0,因此不需要大小写表达式或其他任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM