ใช้ SUBSTRING_INDEX() แยกสตริงด้วยตัวคั่น
สร้างตารางและเพิ่มข้อมูล
mysql> create table DemoTable ( Name varchar(40) ); Query OK, 0 rows affected (1.80 sec)
mysql> insert into DemoTable values('John_Smith');
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable values('Carol_Taylor');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('David_Miller');
Query OK, 1 row affected (0.54 sec)
คิวรี่แยกส่วนแรก (ชื่อ) คั่นด้วย _
mysql> select if(locate('_',Name)=0,'',substring_index(Name, '_', 1)) from DemoTable;
ผลลัพธ์
+---------------------------------------------------------+
| if(locate('_',Name)=0,'',substring_index(Name, '_', 1)) |
+---------------------------------------------------------+
| John |
| Carol |
| David |
+---------------------------------------------------------+
3 rows in set (0.00 sec)
คำอธิบาย: LOCATE('_', Name) หาตำแหน่ง _ | ถ้าไม่เจอ (คืน 0) ให้คืนสตริงว่าง | SUBSTRING_INDEX(Name, '_', 1) ดึงส่วนก่อน _ ตัวแรก | สำหรับส่วนหลัง ใช้ count = -1