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

วิธีสร้างหมายเลขลำดับ (Row Number) ใน MySQL Query

สามารถสร้างหมายเลขลำดับ (Serial Number) ในผลลัพธ์ Query ได้โดยใช้ User-defined Variable

ไวยากรณ์

SELECT @variableName := @variableName + 1 AS aliasName, 
       yourColumn1, yourColumn2, ...
FROM yourTableName, 
     (SELECT @variableName := 0) AS variableName;

ตัวอย่างการใช้งาน

สร้างตาราง tblStudentInformation:

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

เพิ่มข้อมูล:

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

ข้อมูลเดิม

+-------------+------------+------------------+
| StudentName | StudentAge | StudentMathMarks |
+-------------+------------+------------------+
| Carol       | 23         | 89               |
| Bob         | 25         | 92               |
| John        | 21         | 82               |
| David       | 26         | 98               |
+-------------+------------+------------------+

คำสั่งสร้างหมายเลขลำดับ

mysql> SELECT @serialNumber := @serialNumber + 1 AS yourSerialNumber,
    -> StudentName, StudentAge, StudentMathMarks
    -> FROM tblStudentInformation,
    -> (SELECT @serialNumber := 0) AS serialNumber;

ผลลัพธ์พร้อมหมายเลขลำดับ

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

หมายเหตุ: ใน MySQL 8.0+ แนะนำให้ใช้ ROW_NUMBER() OVER () แทนเพื่อประสิทธิภาพและความชัดเจนที่ดีกว่า