要在单个查询中获取最大值和最小值,请使用聚合函数min()
和max()
。让我们首先创建一个表:
mysql> create table DemoTable ( FirstValue int, SecondValue int );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable values(10,30); mysql> insert into DemoTable values(30,60); mysql> insert into DemoTable values(100,500); mysql> insert into DemoTable values(50,80);
以下是使用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)