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

MySQL: เติมศูนย์หน้าหมายเลข Serial แบบมี Hyphen (000-100)

การจัดรูปแบบ Serial Number ด้วย CONCAT และ RIGHT

ใช้ CONCAT('000-', SerialNumber) แล้ว RIGHT(..., 7) ตัดเอา 7 ตัวสุดท้าย ได้รูปแบบ 000-xxx

ตัวอย่าง

mysql> create table DemoTable829(SerialNumber int);
Query OK, 0 rows affected (0.64 sec)
mysql> insert into DemoTable829 values(100);
mysql> insert into DemoTable829 values(101);
mysql> insert into DemoTable829 values(102);
mysql> insert into DemoTable829 values(103);
mysql> insert into DemoTable829 values(104);

คำสั่งจัดรูปแบบ

mysql> select RIGHT(CONCAT('000-', SerialNumber), 7) from DemoTable829;

ผลลัพธ์:

+----------------------------------------+
| RIGHT(CONCAT('000-', SerialNumber), 7) |
+----------------------------------------+
| 000-100                                |
| 000-101                                |
| 000-102                                |
| 000-103                                |
| 000-104                                |
+----------------------------------------+

คำอธิบาย

  • CONCAT('000-', 100) = '000-100' (7 ตัวอักษร)
  • CONCAT('000-', 1000) = '000-1000' (8 ตัวอักษร)
  • RIGHT(..., 7) ตัดเอา 7 ตัวสุดท้าย -> '00-1000' (อาจไม่ได้ผลที่ต้องการถ้าเกิน 3 หลัก)

วิธีที่ยืดหยุ่นกว่า: LPAD

-- ทำให้หมายเลขเป็น 3 หลัก แล้วต่อ -
SELECT CONCAT(LPAD(SerialNumber, 3, '0'), '-') FROM DemoTable829;
-- ผล: 100-, 101-, 102- ... (ต้องการ 000-100 ต้องปรับ Logic)

รูปแบบมาตรฐาน: ใช้ LPAD เต็ม

-- Serial 6 หลัก: 000100, 000101
SELECT LPAD(SerialNumber, 6, '0') FROM DemoTable829;

-- แบบมี Hyphen ทุก 3 หลัก (Complex)
SELECT CONCAT(
    LPAD(FLOOR(SerialNumber/1000), 3, '0'), '-',
    LPAD(SerialNumber % 1000, 3, '0')
) FROM DemoTable829;

สรุป

RIGHT(CONCAT('000-', col), 7) ใช้ได้สำหรับเลข 3 หลัก (100-999) สำหรับช่วงกว้างกว่า ควรใช้ LPAD คำนวณส่วนหน้า/หลังแยกกัน