如何使用 MySQL 查询一列或多列具有相同值的记录?


为此,你可以使用带有子查询的 GROUP BY HAVING。我们首先创建一个表−

mysql> create table DemoTable1861
     (
     Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
     Name varchar(20),
     Marks int
     );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1861(Name,Marks) values('John',45);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1861(Name,Marks) values('Chris',74);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1861(Name,Marks) values('David',89);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1861(Name,Marks) values('Chris',74);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1861(Name,Marks) values('John',49);
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from DemoTable1861;

这将生成以下输出 −

+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
|  1 | John  |    45 |
|  2 | Chris |    74 |
|  3 | David |    89 |
|  4 | Chris |    74 |
|  5 | John  |    49 |
+----+-------+-------+
5 rows in set (0.00 sec)

这里是如何查询一列或多列中具有相同值的记录

mysql> select Id,Name,Marks from DemoTable1861
     where (Name,Marks) IN ( select Name,Marks from DemoTable1861
     group by Name,Marks
     having count(*) > 1);

这将生成以下输出 −

+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
|  2 | Chris |    74 |
|  4 | Chris |    74 |
+----+-------+-------+
2 rows in set (0.00 sec)

更新于: 2019-12-26

376 次浏览

开启您的 职业

通过完成课程获得认证

开始使用
广告
© . All rights reserved.