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

ประโยชน์ของ ZEROFILL ใน MySQL

ZEROFILL คืออะไร?

ZEROFILL จะเติมศูนย์ (0) นำหน้าค่าที่แสดงผล จนครบตามความกว้าง (display width) ที่กำหนดในคอลัมน์

ตัวอย่างเปรียบเทียบ

สร้างตาราง

mysql> create table ZeroFillDemo (
    -> First int(18) zerofill,
    -> Second int(18)
    -> );
Query OK, 0 rows affected (0.63 sec)

เพิ่มข้อมูล

mysql> insert into ZeroFillDemo values(1,1);
Query OK, 1 row affected (0.13 sec)
mysql> insert into ZeroFillDemo values(12,12);
Query OK, 1 row affected (0.15 sec)
mysql> insert into ZeroFillDemo values(123,123);
Query OK, 1 row affected (0.10 sec)
mysql> insert into ZeroFillDemo values(123456789,123456789);
Query OK, 1 row affected (0.20 sec)

ผลลัพธ์

mysql> select * from ZeroFillDemo;
+--------------------+-----------+
| First              | Second    |
+--------------------+-----------+
| 000000000000000001 | 1         |
| 000000000000000012 | 12        |
| 000000000000000123 | 123       |
| 000000000123456789 | 123456789 |
+--------------------+-----------+
4 rows in set (0.00 sec)

สรุป

  • คอลัมน์ First (มี ZEROFILL): แสดงค่าพร้อมศูนย์นำหน้าครบ 18 หลัก
  • คอลัมน์ Second (ไม่มี ZEROFILL): แสดงค่าปกติ
  • ZEROFILL สร้างผลลัพธ์ให้อ่านง่าย สอดคล้องกับรูปแบบที่ต้องการ (เช่น รหัสสินค้า หมายเลขบัญชี)

หมายเหตุ: ZEROFILL ทำงานเฉพาะการแสดงผล ไม่เปลี่ยนค่าที่จัดเก็บจริง