使用 MySQL GROUP BY 和 HAVING 显示具有非重复 Id 的记录
我们首先创建一个表 −
mysql> create table DemoTable ( Id int, ColorName varchar(100) ); Query OK, 0 rows affected (0.56 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable values(100,'Red'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(101,'Green'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(101,'Blue'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values(102,'Yellow'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(100,'Purple'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(100,'Black'); Query OK, 1 row affected (0.26 sec)
使用选择语句从表中显示所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+------+-----------+ | Id | ColorName | +------+-----------+ | 100 | Red | | 101 | Green | | 101 | Blue | | 102 | Yellow | | 100 | Purple | | 100 | Black | +------+-----------+ 6 rows in set (0.00 sec)
以下是显示具有非重复 Id 的记录的查询 −
mysql> select *from DemoTable where Id in(select Id from DemoTable group by Id having count(*) < 2);
这将产生以下输出 −
+------+-----------+ | Id | ColorName | +------+-----------+ | 102 | Yellow | +------+-----------+ 1 row in set (0.07 sec)
广告