根据一列还是两列选择所有重复的 MySQL 行?

mysqlmysqli database

为此,请使用子查询和 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)

相关文章