MySQL 中兩個或多個欄位的最大值?


要了解兩個或多個欄位的最大值,請使用 MySQL 中的 GREATEST() 函式。

語法如下 -

SELECT GREATEST(MAX(yourColumnName1),MAX(yourColumnName2),...............MAX(yourColumnName2) ) from yourTableName;

讓我們透過建立具有兩個以上列的表格來理解上述概念 -

mysql> create table GreatestOfTwoOrMore
   -> (
   -> Marks1 int,
   -> Marks2 int,
   -> Marks3 int
   -> );
Query OK, 0 rows affected (0.57 sec)

這是在表中插入記錄的查詢 -

mysql> insert into GreatestOfTwoOrMore values(23,78,89);
Query OK, 1 row affected (0.16 sec)
mysql> insert into GreatestOfTwoOrMore values(50,100,150);
Query OK, 1 row affected (0.24 sec)
mysql> insert into GreatestOfTwoOrMore values(100,500,2000);
Query OK, 1 row affected (0.15 sec)

使用以下查詢顯示上面插入的所有值 -

mysql> select *from GreatestOfTwoOrMore;

以下是輸出 -

+--------+--------+--------+
| Marks1 | Marks2 | Marks3 |
+--------+--------+--------+
|     23 |     78 |     89 |
|     50 |    100 |    150 |
|    100 |    500 |   2000 |
+--------+--------+--------+
3 rows in set (0.00 sec)

讓我們使用以下查詢實現上述概念來獲取兩個或多個欄位的最大值。

查詢如下 -

mysql> SELECT GREATEST(MAX(marks1),MAX(marks2),MAX(marks3)) from GreatestOfTwoOrMore;

以下是輸出 -

+-----------------------------------------------+
| GREATEST(MAX(marks1),MAX(marks2),MAX(marks3)) |
+-----------------------------------------------+
|                                          2000 |
+-----------------------------------------------+
1 row in set (0.06 sec)

更新於: 30-7-2019

82 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.