คำอธิบาย
ใช้ ABS() หาค่าสัมบูรณ์ของความต่าง แล้ว ORDER BY ความต่างน้อยไปมาก และ LIMIT 1 เพื่อเอาค่าที่ใกล้ที่สุด
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
ProductAmount int );
Query OK, 0 rows affected (0.61 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable(ProductAmount) values(5000); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(ProductAmount) values(6000); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable(ProductAmount) values(7000); Query OK, 1 row affected (0.26 sec)
แสดงข้อมูลทั้งหมด
mysql> select * from DemoTable;
ผลลัพธ์:
+------------+---------------+ | CustomerId | ProductAmount | +------------+---------------+ | 1 | 5000 | | 2 | 6000 | | 3 | 7000 | +------------+---------------+ 3 rows in set (0.00 sec)
คิวรี่หาค่าที่ใกล้ 6990 มากที่สุด
mysql> set @value = 6990; Query OK, 0 rows affected (0.00 sec) mysql> select ProductAmount from DemoTable order by ABS(ProductAmount - @value) LIMIT 1;
ผลลัพธ์
+---------------+ | ProductAmount | +---------------+ | 7000 | +---------------+ 1 row in set (0.00 sec)
คำอธิบายการคำนวณ
| ProductAmount | |ProductAmount - 6990| |
|---|---|
| 5000 | 1990 |
| 6000 | 990 |
| 7000 | 10 |
ค่า 7000 มีความต่างน้อยที่สุด (10) → ใกล้ที่สุด
ขยายความ: หา N ค่าที่ใกล้ที่สุด
SELECT ProductAmount FROM DemoTable ORDER BY ABS(ProductAmount - @value) LIMIT 3;
ประสิทธิภาพ
ต้อง Full Table Scan (ไม่ใช้ Index ได้) หากตารางใหญ่มาก ควรพิจารณา:
- จำกัดช่วงด้วย WHERE (เช่น WHERE ProductAmount BETWEEN @value-1000 AND @value+1000)
- ใช้ Spatial Index (MySQL 8.0+) สำหรับข้อมูลพิกัด