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

ใช้ IN() กับคอลัมน์ที่มี Underscore ใน MySQL (Exact Match เท่านั้น)

เมื่อใช้ IN() กับคอลัมน์ที่มีค่าปน Underscore (เช่น '901_John_Doe') การค้นหา IN('702','1001') จะทำ Exact Match เท่านั้น ไม่จับ '1001_Carol_Taylor' เพราะ Underscore ไม่ใช่ Wildcard ใน IN()

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

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

mysql> create table DemoTable1363 (StudentId varchar(20));
mysql> insert into DemoTable1363 values('901'),('702'),('901_John_Doe'),('1001_Carol_Taylor');

ข้อมูล:

+-------------------+
| StudentId         |
+-------------------+
| 901               |
| 702               |
| 901_John_Doe      |
| 1001_Carol_Taylor |
+-------------------+

คำสั่ง IN('702','1001') - Exact Match

mysql> select * from DemoTable1363 where StudentId IN('702','1001');

ผลลัพธ์ (ได้แค่ 702, ไม่ได้ 1001_Carol_Taylor)

+-----------+
| StudentId |
+-----------+
| 702       |
+-----------+

คำอธิบาย:

  • IN() ตรวจสอบค่าเท่ากันทุกตัวอักษร (Exact String Match)
  • Underscore _ ใน IN() คือตัวอักษรปกติ ไม่ใช่ Wildcard (Wildcard _ ใช้ได้ใน LIKE/REGEXP เท่านั้น)
  • หากต้องการค้นหา Prefix: ใช้ LIKE '1001_%' หรือ StudentId LIKE '1001\\_%' ESCAPE '\\'
  • หากต้องการแยกส่วนก่อน Underscore: ใช้ SUBSTRING_INDEX(StudentId, '_', 1) แล้ว IN()