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

Tạo số thứ tự (serial number) cho kết quả truy vấn MySQL

MySQL không có hàm ROW_NUMBER() trước phiên bản 8.0. Cách truyền thống là dùng biến người dùng (user-defined variable).

Cú pháp (MySQL < 8.0)

SELECT @stt := @stt + 1 AS stt, cot1, cot2, ...
FROM ten_bang, (SELECT @stt := 0) AS init;

Ví dụ minh họa

Tạo bảng tblStudentInformation:

CREATE TABLE tblStudentInformation (
    StudentName VARCHAR(20),
    StudentAge INT,
    StudentMathMarks INT
);

INSERT INTO tblStudentInformation VALUES
('Carol',23,89), ('Bob',25,92), ('John',21,82), ('David',26,98);

Truy vấn có số thứ tự

SELECT @stt := @stt + 1 AS stt, 
       StudentName, StudentAge, StudentMathMarks
FROM tblStudentInformation, (SELECT @stt := 0) AS init;

Kết quả:

+-----+-------------+------------+------------------+
| stt | StudentName | StudentAge | StudentMathMarks |
+-----+-------------+------------+------------------+
|   1 | Carol       |         23 |               89 |
|   2 | Bob         |         25 |               92 |
|   3 | John        |         21 |               82 |
|   4 | David       |         26 |               98 |
+-----+-------------+------------+------------------+

MySQL 8.0+ (Khuyến nghị)

Dùng hàm cửa sổ chuẩn ANSI SQL:

SELECT ROW_NUMBER() OVER (ORDER BY StudentName) AS stt,
       StudentName, StudentAge, StudentMathMarks
FROM tblStudentInformation;

Cách này chuẩn, dễ đọc và hiệu năng tốt hơn.