MySQL 查询获取多个最小值?
mysqlmysqli database更新于 2024/2/4 2:22:00
为此,您可以将子查询与 MIN() 一起使用。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> Name varchar(20), -> Score int -> ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('John',56); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('John',45); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values('John',58); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Chris',43); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Chris',38); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris',87); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | John | 56 | | John | 45 | | John | 58 | | Chris | 43 | | Chris | 38 | | Chris | 87 | +-------+-------+ 6 rows in set (0.00 sec)
这是获取多个最小值的查询 −
mysql> select *from DemoTable tbl1 -> where Score IN( select min(Score) from DemoTable tbl2 where tbl1.Name=tbl2.Name);
这将产生以下输出 −
+-------+-------+ | Name | Score | +-------+-------+ | John | 45 | | Chris | 38 | +-------+-------+ 2 rows in set (0.00 sec)