如何使用 MySQL 查找一个或多个列中具有精确值的行?

mysqlmysqli database更新于 2024/10/15 6:04:17

为此,您可以使用带有子查询的 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)

相关文章


有用资源