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

เพิ่มความแม่นยำในการหารใน MySQL ด้วย CAST AS DECIMAL

เมื่อหารจำนวนเต็มใน MySQL ผลลัพธ์จะเป็นทศนิยม แต่ความแม่นยำอาจไม่เพียงพอ สามารถเพิ่มความแม่นยำได้โดยใช้ CAST() แปลงเป็น DECIMAL(precision, scale) ก่อนทำการหาร

Syntax

SELECT CAST(column_name AS DECIMAL(precision, scale)) / divisor FROM table_name;
  • precision - จำนวนหลักทั้งหมด (สูงสุด 65)
  • scale - จำนวนหลักหลังจุดทศนิยม (สูงสุด 30)

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

1. สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable1823 ( Value int ); Query OK, 0 rows affected (0.00 sec)

mysql> insert into DemoTable1823 values(1); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1823 values(2); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1823 values(3); Query OK, 1 row affected (0.00 sec)

2. หารด้วย 3 โดยเพิ่มความแม่นยำ 20 ตำแหน่ง

mysql> select cast(Value AS DECIMAL(30, 20)) / 3 as Result from DemoTable1823;

ผลลัพธ์:

+----------------------------+
| Result                     |
+----------------------------+
| 0.333333333333333333333333 |
| 0.666666666666666666666667 |
| 1.000000000000000000000000 |
+----------------------------+
3 rows in set (0.00 sec)

เปรียบเทียบความแม่นยำ

-- ไม่ใช้ CAST (ค่าเริ่มต้น)
SELECT 1/3;        -- 0.3333

-- ใช้ CAST DECIMAL(10,5)
SELECT CAST(1 AS DECIMAL(10,5))/3;  -- 0.33333

-- ใช้ CAST DECIMAL(30,20)
SELECT CAST(1 AS DECIMAL(30,20))/3; -- 0.333333333333333333333333

ข้อควรระวัง

  • DECIMAL(65,30) เป็นค่าสูงสุดที่ MySQL รองรับ
  • Precision ต้อง ≥ Scale
  • การหารด้วย 0 จะได้ NULL (ไม่ใช่ Error)
  • ประสิทธิภาพ: DECIMAL ช้ากว่า FLOAT/DOUBLE แต่แม่นยำกว่า (Exact value)

การใช้งานจริง: คำนวณอัตรา/เปอร์เซ็นต์

SELECT 
    CAST(numerator AS DECIMAL(20,10)) / CAST(denominator AS DECIMAL(20,10)) * 100 AS percentage
FROM table_name;

สรุป: ใช้ CAST(value AS DECIMAL(p,s)) ก่อนทำการหารเพื่อควบคุมความแม่นยำทศนิยม เหมาะสำหรับการคำนวณทางการเงิน สถิติ หรือวิทยาศาสตร์ที่ต้องการความแม่นยำสูง