要获取仅在列中出现一次的值的数量,请使用GROUP BY HAVING。让我们首先创建一个表:
mysql> create table DemoTable ( Name varchar(20) );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable values('Larry'); mysql> insert into DemoTable values('Larry'); mysql> insert into DemoTable values('Sam'); mysql> insert into DemoTable values('Chris'); mysql> insert into DemoTable values('Sam'); mysql> insert into DemoTable values('Mike'); mysql> insert into DemoTable values('Sam'); mysql> insert into DemoTable values('Larry'); mysql> insert into DemoTable values('Mike'); mysql> insert into DemoTable values('Mike'); mysql> insert into DemoTable values('Carol'); mysql> insert into DemoTable values('Robert');
以下是使用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)