從 3 個不同的列中獲取 MySQL 最大值?


要從三列中獲取最大值,請使用 GREATEST() 函式。

語法如下

SELECT GREATEST(yourColumnName1,yourColumnName2,yourColumnName3) AS anyAliasName FROM yourTableName;

為了理解以上語法,讓我們建立一個表。建立表的查詢如下

mysql> create table MaxOfThreeColumnsDemo
   -> (
   -> First int,
   -> Second int,
   -> Third int
   -> );
Query OK, 0 rows affected (0.73 sec)

使用插入命令在表中插入一些記錄。

查詢如下

mysql> insert into MaxOfThreeColumnsDemo values(30,90,60);
Query OK, 1 row affected (0.16 sec)
mysql> insert into MaxOfThreeColumnsDemo values(100,40,50);
Query OK, 1 row affected (0.20 sec)
mysql> insert into MaxOfThreeColumnsDemo values(101,290,150);
Query OK, 1 row affected (0.22 sec)

使用 select 語句從表中顯示所有記錄。

查詢如下

mysql> select *from MaxOfThreeColumnsDemo;

以下是輸出

+-------+--------+-------+
| First | Second | Third |
+-------+--------+-------+
| 30    | 90     | 60    |
| 100   | 40     | 50    |
| 101   | 290    | 150   |
+-------+--------+-------+
3 rows in set (0.00 sec)

以下是查詢三個列中最大值點的查詢

mysql> select greatest(First,Second,Third) AS MAXValueOfThreeColumns from MaxOfThreeColumnsDemo;

以下是輸出

+------------------------+
| MAXValueOfThreeColumns |
+------------------------+
| 90                     |
| 100                    |
| 290                    |
+------------------------+
3 rows in set (0.00 sec)

更新於:30-Jul-2019

6 千次觀看

開啟您的職業

完成課程認證

開始
廣告
© . All rights reserved.