基于一或两列选择所有重复的 MySQL 行?


为此,请将子查询与 HAVING 子句结合使用。我们首先创建一个表−

mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(20),
   StudentLastName varchar(20)
   );
Query OK, 0 rows affected (0.27 sec)

使用 insert 命令在表中插入一些记录−

mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Smith');
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('Carol','Taylor');
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Doe');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('John','Brown');
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(StudentFirstName,StudentLastName) values('David','Miller');
Query OK, 1 row affected (0.06 sec)

使用 select 语句显示表中的所有记录−

mysql> select *from DemoTable;

这将产生以下输出−

+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
| 1         | John             | Smith           |
| 2         | Carol            | Taylor          |
| 3         | John             | Doe             |
| 4         | John             | Brown           |
| 5         | David            | Miller          |
+-----------+------------------+-----------------+
5 rows in set (0.00 sec)

以下是基于一或两列选择所有重复行的查询。在此,我们计算出现次数超过一次的名字,即重复项−

mysql> select StudentId from DemoTable
   where StudentFirstName=(select StudentFirstName from DemoTable having count(StudentFirstName) > 1);

这将产生以下输出−

+-----------+
| StudentId |
+-----------+
| 1         |
| 3         |
| 4         |
+-----------+
3 rows in set (0.03 sec)

更新时间:30-Jul-2019

469 次浏览

开启你的职业生涯

通过完成课程取得认证

开始吧
广告
© . All rights reserved.