通过一个 MySQL 查询获取特定列值的多重计数
为此,你可以对特定列使用聚合函数 sum() 和参数值。我们先创建一个表 -
mysql> create table DemoTable1790 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20), Score int ); Query OK, 0 rows affected (0.94 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1790(Name,Score) values('Chris',45); Query OK, 1 row affected (0.38 sec) mysql> insert into DemoTable1790(Name,Score) values('David',55); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1790(Name,Score) values('David',98); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1790(Name,Score) values('Chris',91); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1790(Name,Score) values('Mike',99); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1790(Name,Score) values('Carol',55); Query OK, 1 row affected (0.35 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1790;
这将生成以下输出 -
+----+-------+-------+ | Id | Name | Score | +----+-------+-------+ | 1 | Chris | 45 | | 2 | David | 55 | | 3 | David | 98 | | 4 | Chris | 91 | | 5 | Mike | 99 | | 6 | Carol | 55 | +----+-------+-------+ 6 rows in set (0.00 sec)
以下是对单一 MySQL 查询中的多重计数 -
mysql> select sum(Name='Chris'),sum(Score=55) from DemoTable1790;
这将生成以下输出 -
+-------------------+---------------+ | sum(Name='Chris') | sum(Score=55) | +-------------------+---------------+ | 2 | 2 | +-------------------+---------------+ 1 row in set (0.00 sec)
广告