为此,可以使用GROUP BY HAVING子句。让我们首先创建一个表-
mysql> create table DemoTable1467 -> ( -> Id int, -> Name varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1467 values(100,'Chris'); mysql> insert into DemoTable1467 values(110,'David'); mysql> insert into DemoTable1467 values(120,'Mike'); mysql> insert into DemoTable1467 values(100,'Chris'); mysql> insert into DemoTable1467 values(130,'Carol'); mysql> insert into DemoTable1467 values(100,'Chris');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1467;
这将产生以下输出-
+------+-------+ | Id | Name | +------+-------+ | 100 | Chris | | 110 | David | | 120 | Mike | | 100 | Chris | | 130 | Carol | | 100 | Chris | +------+-------+ 6 rows in set (0.00 sec)
这是从同一表中获取具有相同值但具有不同ID的行的查询-
mysql> select Id,Name,count(*) as IdCount from DemoTable1467 -> group by Id -> having IdCount > 2;
这将产生以下输出-
+------+-------+---------+ | Id | Name | IdCount | +------+-------+---------+ | 100 | Chris | 3 | +------+-------+---------+ 1 row in set (0.00 sec)