仅显示出现在 MySQL 中至少三次以上的重复列名称


为此请使用 HAVING COUNT()。我们先创建一个表 -

mysql> create table DemoTable1351
    -> (
    -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> StudentName varchar(40)
    -> );
Query OK, 0 rows affected (1.08 sec)

使用插入命令向表中插入一些记录 -

mysql> insert into DemoTable1351(StudentName) values('Chris');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1351(StudentName) values('Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1351(StudentName) values('Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1351(StudentName) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1351(StudentName) values('Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1351(StudentName) values('David');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1351(StudentName) values('Bob');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1351(StudentName) values('Mike');
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable1351(StudentName) values('David');
Query OK, 1 row affected (0.12 sec)

使用 select 语句从表中显示所有记录 -

mysql> select * from DemoTable1351;

这会生成以下输出 -

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Bob         |
|         3 | Bob         |
|         4 | David       |
|         5 | Bob         |
|         6 | David       |
|         7 | Bob         |
|         8 | Mike        |
|         9 | David       |
+-----------+-------------+
9 rows in set (0.00 sec)

以下是对出现在至少三次的重复列名称的显示查询 -

mysql> select * from DemoTable1351
    -> group by StudentName
    -> having count(StudentName) >=3;

这会生成以下输出 -

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         2 | Bob         |
|         4 | David       |
+-----------+-------------+
2 rows in set (0.00 sec)

更新于: 2019-11-05

68 次浏览

开启你的 职业 生涯

完成课程并获取认证

开始
广告