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

เพิ่มตัวคั่นหมายเลข (Thousands Separator) ใน MySQL ด้วย View

การจัดรูปแบบตัวเลขด้วยคอมม่าคั่นพัน (Thousands Separator) ใน MySQL ผ่าน View

ใช้ฟังก์ชัน FORMAT(number, decimals) จัดรูปแบบตัวเลขพร้อมคอมม่า แล้วสร้าง View เพื่อใช้งานสะดวก

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

สร้างตารางและเพิ่มตัวเลขใหญ่:

mysql> create table DemoTable (StudentId int);
mysql> insert into DemoTable values(343898456);
mysql> insert into DemoTable values(222333444);

ข้อมูลต้นฉบับ:

+-----------+
| StudentId |
+-----------+
| 343898456 |
| 222333444 |
+-----------+

สร้าง View ใช้ FORMAT (0 ทศนิยม):

mysql> create view myView_DemoTable as select format(StudentId, 0) AS `StudentId` from DemoTable;
Query OK, 0 rows affected (0.18 sec)

Query ผ่าน View:

mysql> select * from myView_DemoTable;
+-------------+
| StudentId   |
+-------------+
| 343,898,456 |
| 222,333,444 |
+-------------+

คุณสมบัติของ FORMAT():

  • คืนค่าเป็น String (VARCHAR) ไม่ใช่ Number
  • พารามิเตอร์ที่ 2 = จำนวนทศนิยม (0 = ไม่มีทศนิยม)
  • ใช้ Locale ของ Server สำหรับ Decimal Point และ Thousands Separator
  • ค่าลบ: FORMAT(-1234.56, 2) → '-1,234.56'

ข้อควรระวัง: ผลลัพธ์เป็น String ไม่สามารถคำนวณต่อได้ | หากต้องคำนวณ ให้ใช้คอลัมน์ต้นฉบับ | View เหมาะสำหรับการแสดงผล (Reporting/Export) เท่านั้น