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

การค้นหาตัวเลขในคอลัมน์ที่คั่นด้วย comma ด้วย FIND_IN_SET ใน MySQL

เมื่อเก็บข้อมูลหลายค่าในคอลัมน์เดียวคั่นด้วย comma สามารถค้นหาค่าเฉพาะได้ด้วยฟังก์ชัน FIND_IN_SET()

สร้างตารางตัวอย่าง

mysql> create table DemoTable ( 
    ListOfNumbers varchar(100) ); 
Query OK, 0 rows affected (1.24 sec)

เพิ่มข้อมูลตัวอย่าง

mysql> insert into DemoTable values('784,746,894,344'); Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('456,322,333,456'); Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('654,785,678,456'); Query OK, 1 row affected (0.47 sec)
mysql> insert into DemoTable values('123,676,847,785'); Query OK, 1 row affected (0.34 sec)

แสดงข้อมูลทั้งหมด

mysql> select *from DemoTable;
+-----------------+
| ListOfNumbers   |
+-----------------+
| 784,746,894,344 |
| 456,322,333,456 |
| 654,785,678,456 |
| 123,676,847,785 |
+-----------------+
4 rows in set (0.00 sec)

คิวรี่ค้นหาแถวที่มีเลข 456

mysql> select *from DemoTable where find_in_set('456',ListOfNumbers);

ผลลัพธ์:

+-----------------+
| ListOfNumbers   |
+-----------------+
| 456,322,333,456 |
| 654,785,678,456 |
+-----------------+
2 rows in set (0.28 sec)

คำอธิบาย FIND_IN_SET

  • FIND_IN_SET(str, strlist) คืนค่าตำแหน่ง (1-based) ของ str ใน strlist
  • คืนค่า 0 หากไม่พบ หรือ NULL หากอาร์กิวเมนต์เป็น NULL
  • strlist ต้องคั่นด้วย comma (,) เท่านั้น ไม่มีช่องว่าง

ข้อจำกัดและแนวทางแก้ไข

  • ไม่ใช้ Index ได้ - Full table scan ทุกครั้ง
  • ข้อจำกัดความยาว - VARCHAR จำกัดความยาว
  • แนวทางที่ดีกว่า: ใช้ตารางความสัมพันธ์ (Junction Table) แทน

ตัวอย่างตารางความสัมพันธ์ (Best Practice)

CREATE TABLE items (id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE tags (id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE item_tags (item_id INT, tag_id INT, PRIMARY KEY(item_id, tag_id));