选择 MySQL 表中每个值的最大值?
mysqlmysqli database
为此,请使用 GROUP BY 子句和 MAX()。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> CountryName varchar(20), -> Population int -> ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('US',560); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('UK',10090); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('UK',8794); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('US',1090); Query OK, 1 row affected (0.21 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+-------------+------------+ | CountryName | Population | +-------------+------------+ | US | 560 | | UK | 10090 | | UK | 8794 | | US | 1090 | +-------------+------------+ 4 rows in set (0.00 sec)
以下是选择 MySQL 表中每个值的最大值的查询 −
mysql> select CountryName,max(Population) from DemoTable group by CountryName;
这将产生以下输出 −
+-------------+-----------------+ | CountryName | max(Population) | +-------------+-----------------+ | US | 1090 | | UK | 10090 | +-------------+-----------------+ 2 rows in set (0.00 sec)