为了在MySQL中获得最大的两列值,您需要使用GREATEST()
function。以下是语法:
select greatest(yourColumnName1,yourColumnName2) AS anyAliasName from yourTableName;
让我们首先创建一个表:
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Number1 int, Number2 int );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable(Number1,Number2) values(1000,10000); mysql> insert into DemoTable(Number1,Number2) values(600,900); mysql> insert into DemoTable(Number1,Number2) values(12,9); mysql> insert into DemoTable(Number1,Number2) values(19,56);
以下是使用select命令显示表中记录的查询:
mysql> select *from DemoTable;
这将产生以下输出:
+----+---------+---------+ | Id | Number1 | Number2 | +----+---------+---------+ | 1 | 1000 | 10000 | | 2 | 600 | 900 | | 3 | 12 | 9 | | 4 | 19 | 56 | +----+---------+---------+ 4 rows in set (0.00 sec)
以下是查询以获取MySQL中两个列的最大值的查询:
mysql> select greatest(Number1,Number2) AS MAXIMUM_NUMBER_OF_TWO_COLUMNS from DemoTable;
这将产生以下输出:
+-------------------------------+ | MAXIMUM_NUMBER_OF_TWO_COLUMNS | +-------------------------------+ | 10000 | | 900 | | 12 | | 56 | +-------------------------------+ 4 rows in set (0.00 sec)
在上面,您可以看到1000和10000中显示的值是10000,即最大值。以锯切的方式,它适用于其他人,即600和900中的900。