要从MySQL表的一部分中选择最小值和最大值,请使用以下语法-
select min(yourColumnName) as yourAliasName1,max(yourColumnName) as yourAliasName2 from (select yourColumnName from yourTableName limit yourLimitValue) tbl1;
让我们首先创建一个表。以下是查询-
mysql> create table MinAndMaxValueDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Value int -> );
使用insert命令在表中插入记录。以下是查询-
mysql> insert into MinAndMaxValueDemo(Value) values(10); mysql> insert into MinAndMaxValueDemo(Value) values(100); mysql> insert into MinAndMaxValueDemo(Value) values(50); mysql> insert into MinAndMaxValueDemo(Value) values(40);
以下是使用select语句显示表中所有记录的查询-
mysql> select * from MinAndMaxValueDemo;
这将产生以下输出-
+----+-------+ | Id | Value | +----+-------+ | 1 | 10 | | 2 | 100 | | 3 | 50 | | 4 | 40 | +----+-------+ 4 rows in set (0.00 sec)
以下是从MySQL的表部分中选择最小值和最大值的查询-
mysql> select min(Value) as MinimumValue,max(Value) as MaximumValue from -> (select Value from MinAndMaxValueDemo limit 3) tbl1;
这将产生以下输出-
+--------------+--------------+ | MinimumValue | MaximumValue | +--------------+--------------+ | 10 | 100 | +--------------+--------------+ 1 row in set (0.07 sec)