以下是语法-
select sum(yourColumnName1+yourColumnName2+yourColumnName3...N) as `anyAliasName1`, sum(yourColumnName1 and yourColumnName2 and yourColumnName3….N) as anyAliasName from yourTableName;
让我们创建一个表-
mysql> create table demo36 −> ( −> id int not null auto_increment primary key, −> value1 int, −> value2 int, −> value3 int −> );
借助insert命令将一些记录插入表中-
mysql> insert into demo36(value1,value2,value3) values(1,0,0); mysql> insert into demo36(value1,value2,value3) values(1,0,1); mysql> insert into demo36(value1,value2,value3) values(1,1,1); mysql> insert into demo36(value1,value2,value3) values(0,1,0); mysql> insert into demo36(value1,value2,value3) values(1,1,0);
使用select语句显示表中的记录-
mysql> select *from demo36;
这将产生以下输出-
+----+--------+--------+--------+ | id | value1 | value2 | value3 | +----+--------+--------+--------+ | 1 | 1 | 0 | 0 | | 2 | 1 | 0 | 1 | | 3 | 1 | 1 | 1 | | 4 | 0 | 1 | 0 | | 5 | 1 | 1 | 0 | +----+--------+--------+--------+ 5 rows in set (0.00 sec)
以下是对MySQL中具有特定值的列数进行计数的查询-
mysql> select −> sum(value1+value2+value3) as `Total_Number_Of_1`, −> sum(value1 and value2 and value3) as `Total_Number_Of_Rows_With_1` −> from demo36;
这将产生以下输出-
+-------------------+-----------------------------+ | Total_Number_Of_1 | Total_Number_Of_Rows_With_1 | +-------------------+-----------------------------+ | 9 | 1 | +-------------------+-----------------------------+ 1 row in set (0.00 sec)