如何在 MySQL 中使用 COUNT 执行 SELECT?
mysqlmysqli database
要使用 COUNT 执行 SELECT,请使用聚合函数 COUNT()。让我们首先创建一个表 −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(100), Subject varchar(100) ); Query OK, 0 rows affected (0.54 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(Name,Subject) values('John','MySQL'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(Name,Subject) values('John','Java'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(Name,Subject) values('Carol','MongoDB'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Name,Subject) values('Carol','Java'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Name,Subject) values('Carol','MySQL'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(Name,Subject) values('John','MySQL'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(Name,Subject) values('Carol','MongoDB'); Query OK, 1 row affected (0.26 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+----+-------+---------+ | Id | Name | Subject | +----+-------+---------+ | 1 | John | MySQL | | 2 | John | Java | | 3 | Carol | MongoDB | | 4 | Carol | Java | | 5 | Carol | MySQL | | 6 | John | MySQL | | 7 | Carol | MongoDB | +----+-------+---------+ 7 rows in set (0.00 sec)
以下是在 MySQL 中使用 count 进行选择的查询 −
mysql> select Name,Subject,count(Subject) from DemoTable group by Subject,Name;
输出
+-------+---------+----------------+ | Name | Subject | count(Subject) | +-------+---------+----------------+ | John | MySQL | 2 | | John | Java | 1 | | Carol | MongoDB | 2 | | Carol | Java | 1 | | Carol | MySQL | 1 | +-------+---------+----------------+ 5 rows in set (0.00 sec)