ปัญหา
คอลัมน์ VARCHAR ที่เก็บตัวเลข (เช่น '1083745') เปรียบเทียบแบบ string จะผิด (เช่น '9' > '10') ต้องแปลงเป็นตัวเลขก่อน
วิธีแก้: ใช้ CAST()
รูปแบบคำสั่ง
SELECT * FROM yourTableName WHERE CAST(yourColumnName AS SIGNED) = yourIntegerValue;
ตัวอย่างครบถ้วน
1. สร้างตารางเก็บ ID เป็น VARCHAR
mysql> create table compareTwoStringDemo
-> (
-> UserId varchar(100)
-> );
Query OK, 0 rows affected (0.78 sec)
2. เพิ่มข้อมูลตัวเลขใน string
mysql> insert into compareTwoStringDemo values('1083745');
Query OK, 1 row affected (0.12 sec)
mysql> insert into compareTwoStringDemo values('9867585');
Query OK, 1 row affected (0.11 sec)
mysql> insert into compareTwoStringDemo values('3547483');
Query OK, 1 row affected (0.15 sec)
mysql> insert into compareTwoStringDemo values('9845646');
Query OK, 1 row affected (0.15 sec)
mysql> insert into compareTwoStringDemo values('9876532');
Query OK, 1 row affected (0.10 sec)
3. ดูข้อมูล
mysql> select * from compareTwoStringDemo;
+---------+ | UserId | +---------+ | 1083745 | | 9867585 | | 3547483 | | 9845646 | | 9876532 | +---------+
4. เปรียบเทียบด้วย CAST (ค้นหา 3547483)
mysql> select * from compareTwoStringDemo
-> where cast(UserId as signed) = 3547483;
+---------+ | UserId | +---------+ | 3547483 | +---------+
CAST Types ที่ใช้ได้
| Type | ช่วงค่า | ใช้เมื่อ |
|---|---|---|
| SIGNED | -2147483648 ถึง 2147483647 | Integer ทั่วไป (default) |
| UNSIGNED | 0 ถึง 4294967295 | Integer ไม่ติดลบ |
| DECIMAL(M,D) | ตาม M,D | ทศนิยมแม่นยำ |
| CHAR(N) | String ความยาว N | แปลงกลับเป็น string |
วิธีอื่น: CONVERT()
SELECT * FROM table WHERE CONVERT(UserId, SIGNED) = 3547483;
กรณีเปรียบเทียบ String กับ String (ไม่แปลง)
-- ผิด: '9' > '10' (string compare)
SELECT '9' > '10'; -- 1 (true) ❌
-- ถูก: แปลงก่อน
SELECT CAST('9' AS SIGNED) > CAST('10' AS SIGNED); -- 0 (false) ✓
แนะนำ: เก็บตัวเลขในชนิด INT/BIGINT ตั้งแต่แรก จะได้ไม่ต้อง CAST ทุกครั้ง และ index ทำงานได้เต็มที่