如何通过多列查看 MySQL 表中的重复值?


要查看 MySQL 中的重复值,可以使用分组后使用 having 子句。语法如下。

select yourColumnName1,yourColumnName2,......N,count(*) as anyVariableName from
yourTableName
group by yourColumnName1,yourColumnName2
having count(*) > 1;

为了理解上述语法,我们创建一个表。创建表的查询如下。

mysql> create table DuplicateDemo
-> (
-> StudentId int not null,
-> StudentFirstName varchar(100),
-> StudentLastName varchar(100),
-> Primary Key(StudentId)
-> );
Query OK, 0 rows affected (0.50 sec)

使用 insert 命令在表中插入一些记录。查询如下。

mysql> insert into DuplicateDemo values(1,'John','Smith');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DuplicateDemo values(2,'Mike','Jones');
Query OK, 1 row affected (0.28 sec)

mysql> insert into DuplicateDemo values(3,'David','Smith');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DuplicateDemo values(4,'Carol','Taylor');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DuplicateDemo values(5,'David','Smith');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DuplicateDemo values(6,'John','Smith');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DuplicateDemo values(7,'John','Taylor');
Query OK, 1 row affected (0.15 sec)

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

查询如下 -

mysql> select *from DuplicateDemo;

以下是输出。

+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
| 1         | John             | Smith           |
| 2         | Mike             | Jones           |
| 3         | David            | Smith           |
| 4         | Carol            | Taylor          |
| 5         | David            | Smith           |
| 6         | John             | Smith           |
| 7         | John             | Taylor          |
+-----------+------------------+-----------------+
7 rows in set (0.00 sec)

以下是检查表中重复值的查询。

mysql> select StudentFirstName,StudentLastName,count(*) as Total from DuplicateDemo
-> group by StudentFirstName,StudentLastName
-> having count(*) > 1;

以下是输出。

+------------------+-----------------+-------+
| StudentFirstName | StudentLastName | Total |
+------------------+-----------------+-------+
| John             | Smith           | 2     |
| David            | Smith           | 2     |
+------------------+-----------------+-------+
2 rows in set (0.00 sec)

更新于:30-7-2019

2K+ 浏览次数

开启你的 职业

通过完成课程获得认证

开始
广告