如何在一个 MySQL 查询同时获得最大和最小值?
要在一个查询中获得最大值和最小值,请使用聚合函数 min() 和 max()。我们首先创建一个表
mysql> create table DemoTable ( FirstValue int, SecondValue int ); Query OK, 0 rows affected (0.66 sec)
以下是使用 insert 命令向表中插入一些记录的查询
mysql> insert into DemoTable values(10,30); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(30,60); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(100,500); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(50,80); Query OK, 1 row affected (0.18 sec)
以下是使用 select 命令从表中显示记录的查询
mysql> select *from DemoTable;
这将产生以下输出
+------------+-------------+ | FirstValue | SecondValue | +------------+-------------+ | 10 | 30 | | 30 | 60 | | 100 | 500 | | 50 | 80 | +------------+-------------+ 4 rows in set (0.00 sec)
以下是获取单个查询最大值和最小值的查询
mysql> select min(FirstValue),min(SecondValue),max(FirstValue),max(SecondValue) from DemoTable;
这将产生以下输出
+-----------------+------------------+-----------------+------------------+ | min(FirstValue) | min(SecondValue) | max(FirstValue) | max(SecondValue) | +-----------------+------------------+-----------------+------------------+ | 10 | 30 | 100 | 500 | +-----------------+------------------+-----------------+------------------+ 1 row in set (0.00 sec)
广告