Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

หาค่าสูงสุดจากหลายคอลัมน์ใน MySQL (GREATEST)

ฟังก์ชัน GREATEST()

คืนค่ามากที่สุดจากรายการค่าที่ให้มา

รูปแบบเพื่อหาค่าสูงสุดของแต่ละคอลัมน์ แล้วหาค่าสูงสุดของทั้งหมด

SELECT GREATEST(MAX(col1), MAX(col2), MAX(col3)) FROM yourTable;

ตัวอย่าง

สร้างตาราง 3 คอลัมน์คะแนน

mysql> create table GreatestOfTwoOrMore (Marks1 int, Marks2 int, Marks3 int);
mysql> insert into GreatestOfTwoOrMore values(23,78,89),(50,100,150),(100,500,2000);

ข้อมูล

+--------+--------+--------+
| Marks1 | Marks2 | Marks3 |
+--------+--------+--------+
| 23     | 78     | 89     |
| 50     | 100    | 150    |
| 100    | 500    | 2000   |
+--------+--------+--------+

หาค่าสูงสุดรวม

mysql> SELECT GREATEST(MAX(marks1), MAX(marks2), MAX(marks3)) from GreatestOfTwoOrMore;
+-----------------------------------------------+
| GREATEST(MAX(marks1), MAX(marks2), MAX(marks3)) |
+-----------------------------------------------+
| 2000                                          |
+-----------------------------------------------+

ฟังก์ชันคู่: LEAST()

หาค่าน้อยที่สุด: LEAST(MIN(col1), MIN(col2), ...)

ใช้กับแถวเดียว (Row-wise)

SELECT GREATEST(Marks1, Marks2, Marks3) FROM GreatestOfTwoOrMore;

คืนค่าสูงสุดของแต่ละแถวแยกกัน