เพิ่มหมายเลขลำดับ (Row Number) ในผลลัพธ์ SELECT
ใช้ User Variable @counter เพิ่มทีละ 1 ในแต่ละแถว
รูปแบบคำสั่ง (Syntax)
SET @counter = 0;
SELECT column_name, @counter := @counter + 1 AS row_number
FROM yourTableName;
ตัวอย่างการใช้งาน
สร้างตาราง incrementCounterDemo:
CREATE TABLE incrementCounterDemo (
Name VARCHAR(100)
);
INSERT INTO incrementCounterDemo VALUES
('John'), ('Carol'), ('David'), ('Mike'), ('Bob'), ('Sam');
สร้าง Running Number:
SET @counter = 0;
SELECT Name, @counter := @counter + 1 AS IncrementingValuebyOne
FROM incrementCounterDemo;
ผลลัพธ์:
| Name | IncrementingValuebyOne |
|---|---|
| John | 1 |
| Carol | 2 |
| David | 3 |
| Mike | 4 |
| Bob | 5 |
| Sam | 6 |
MySQL 8.0+ ใช้ Window Function (แนะนำ)
SELECT Name, ROW_NUMBER() OVER (ORDER BY Name) AS row_num
FROM incrementCounterDemo;
Window Functions ที่เกี่ยวข้อง:
ROW_NUMBER()- 1,2,3... ไม่ข้ามRANK()- 1,2,2,4... ข้ามเมื่อค่าเท่ากันDENSE_RANK()- 1,2,2,3... ไม่ข้ามเมื่อค่าเท่ากัน
ข้อควรระวัง User Variable: ลำดับการประเมินไม่ได้รับการรับประกันใน Query ซับซ้อน (JOIN, SUBQUERY, ORDER BY) ควรใช้ Window Function แทนใน Production