Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Truy vấn MySQL chọn top N hàng hiệu quả

Sử dụng INDEX để chọn top N hàng hiệu quả.

Tạo bảng demo

mysql> create table DemoTable (StudentName varchar(100), StudentScore int);
Query OK, 0 rows affected (0.66 sec)

Chèn 9 bản ghi

mysql> insert into DemoTable values('John', 34);
Query OK, 1 row affected (0.19 sec)
... (các bản ghi Carol 55, Bob 58, Sam 38, Mike 48, Adam 41, Chris 47, Robert 40, David 89)

Hiển thị tất cả

mysql> select * from DemoTable;

Kết quả

+-------------+--------------+
| StudentName | StudentScore |
+-------------+--------------+
| John        | 34           |
| Carol       | 55           |
| Bob         | 58           |
| Sam         | 38           |
| Mike        | 48           |
| Adam        | 41           |
| Chris       | 47           |
| Robert      | 40           |
| David       | 89           |
+-------------+--------------+
9 rows in set (0.00 sec)

Tạo composite index và truy vấn top 3 sau khi bỏ 5 hàng (LIMIT 5, 3)

mysql> alter table DemoTable ADD INDEX name_score(StudentName, StudentScore);
Query OK, 0 rows affected (0.61 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> select StudentName, StudentScore from DemoTable order by StudentScore LIMIT 5, 3;

Kết quả - 3 hàng tiếp theo sau top 5 (theo Score tăng dần)

+-------------+--------------+
| StudentName | StudentScore |
+-------------+--------------+
| Mike        | 48           |
| Carol       | 55           |
| Bob         | 58           |
+-------------+--------------+
3 rows in set (0.00 sec)

Giải thích:

  • ORDER BY StudentScore: Sắp xếp theo điểm tăng dần.
  • LIMIT 5, 3: Bỏ qua 5 hàng đầu (offset=5), lấy 3 hàng tiếp theo.
  • Index (StudentName, StudentScore) hỗ trợ cả WHERE trên StudentName và ORDER BY StudentScore.

Mẹo hiệu năng cho Top-N:

  • Luôn có ORDER BY + LIMIT.
  • Tạo index phù hợp với ORDER BY (covering index nếu SELECT ít cột).
  • Tránh OFFSET lớn (ví dụ LIMIT 100000, 10) → dùng keyset pagination (WHERE id > last_id ORDER BY id LIMIT 10).
  • EXPLAIN để kiểm tra dùng index (type=ref/range, Extra=Using index).