获取仅在 MySQL 列中出现一次的值的计数?
要获取仅在列中出现一次的值的数量,请使用 GROUP BY HAVING。让我们首先创建一个表
mysql> create table DemoTable ( Name varchar(20) ); Query OK, 0 rows affected (0.55 sec)
以下是使用 insert 命令在表中插入一些记录的查询
mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.27 sec)
以下是使用 select 命令从表中显示记录的查询
mysql> select *from DemoTable;
将生成以下输出
+--------+ | Name | +--------+ | Larry | | Larry | | Sam | | Chris | | Sam | | Mike | | Sam | | Larry | | Mike | | Mike | | Carol | | Robert | +--------+ 12 rows in set (0.00 sec)
以下是计算仅在列中出现一次的值的数量的查询,即在“姓名”列中仅出现一次的姓名的数量
mysql> SELECT COUNT(Name) FROM ( SELECT Name FROM DemoTable GROUP BY Name HAVING COUNT(*) = 1 ) AS APPEAR_FIRST_TIME;
将生成以下输出
+-------------+ | COUNT(Name) | +-------------+ | 3 | +-------------+ 1 row in set (0.00 sec)
广告