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

ดึง 3 เรคคอร์ดที่มีค่าสูงสุดใน MySQL

ใช้ ORDER BY DESC และ LIMIT จำกัดจำนวนแถว

สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable1614 ( StudentName varchar(20), StudentScore int ); 
Query OK, 0 rows affected (0.78 sec)
mysql> insert into DemoTable1614 values('Adam',65); 
Query OK, 1 row affected (0.14 sec) 
mysql> insert into DemoTable1614 values('Chris',89); 
Query OK, 1 row affected (0.13 sec) 
mysql> insert into DemoTable1614 values('Bob',58); 
Query OK, 1 row affected (0.22 sec) 
mysql> insert into DemoTable1614 values('Sam',98); 
Query OK, 1 row affected (0.16 sec) 
mysql> insert into DemoTable1614 values('Mike',87); 
Query OK, 1 row affected (0.18 sec) 
mysql> insert into DemoTable1614 values('Carol',79); 
Query OK, 1 row affected (0.12 sec)

คิวรี่ดึง 3 อันดับแรก

mysql> select * from DemoTable1614 order by StudentScore DESC LIMIT 3;

ผลลัพธ์

+-------------+--------------+ 
| StudentName | StudentScore | 
+-------------+--------------+ 
| Sam         |           98 | 
| Chris       |           89 | 
| Mike        |           87 | 
+-------------+--------------+ 
3 rows in set (0.00 sec)

ORDER BY column DESC เรียงมากไปน้อย | LIMIT 3 จำกัด 3 แถวแรก | รวมใช้ได้ Top-N query