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)
阅读更多:MySQL 教程
极客教程