为此,您可以使用聚合函数SUM()。让我们首先创建一个表-
create table DemoTable ( isMarried tinyint(1) );
使用插入命令在表中插入一些记录-
insert into DemoTable values(0); insert into DemoTable values(1); insert into DemoTable values(1); insert into DemoTable values(0); insert into DemoTable values(1); insert into DemoTable values(1); insert into DemoTable values(0);
使用select语句显示表中的所有记录-
select *from DemoTable;
这将产生以下输出-
+-----------+ | isMarried | +-----------+ | 0 | | 1 | | 1 | | 0 | | 1 | | 1 | | 0 | +-----------+ 7 rows in set (0.00 sec)
以下是查询以从一栏中计算0和1的数目并将其显示在两栏中的查询-
select sum(tbl.isMarried=1) as all_one_count, sum(tbl.isMarried=0) as all_zero_count, sum(tbl.isMarried in(0,1)) as all_zero_count_and_one_count from DemoTable tbl;
这将产生以下输出-
+---------------+----------------+------------------------------+ | all_one_count | all_zero_count | all_zero_count_and_one_count | +---------------+----------------+------------------------------+ | 4 | 3 | 7 | +---------------+----------------+------------------------------+ 1 row in set (0.04 sec)