在 MySQL 中获取 MAX 和 MIN 值以及它们的行 ID?
你可以为此使用聚合函数 MAX() 和 MIN()。
让我们首先创建一个表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Number1 int, Number2 int ); Query OK, 0 rows affected (0.89 sec)
使用 insert 命令在表中插入记录 -
mysql> insert into DemoTable(Number1,Number2) values(67,45); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(Number1,Number2) values(90,40); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(Number1,Number2) values(80,43); Query OK, 1 row affected (0.48 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable ;
这将产生以下输出 -
+----+---------+---------+ | Id | Number1 | Number2 | +----+---------+---------+ | 1 | 67 | 45 | | 2 | 90 | 40 | | 3 | 80 | 43 | +----+---------+---------+ 3 rows in set (0.00 sec)
以下是获取 MAX 和 MIN 值及其行 ID 的查询 -
mysql> select * from DemoTable where Number1 = (select max(Number1) from DemoTable) or Number2 = (select min(Number2) from DemoTable);
这将产生以下输出 -
+----+---------+---------+ | Id | Number1 | Number2 | +----+---------+---------+ | 2 | 90 | 40 | +----+---------+---------+ 1 row in set (0.00 sec)
广告