เมื่อต้องการลบส่วนท้ายของสตริงที่อยู่หลังช่องว่าง (เช่น หน่วย "Gigabytes") สามารถใช้ LEFT() ร่วมกับ INSTR() หาตำแหน่งช่องว่าง แล้วตัดเอาเฉพาะส่วนหน้า
ตัวอย่างการสร้างตาราง
mysql> create table DemoTable (
Download varchar(100) );
Query OK, 0 rows affected (0.53 sec)
เพิ่มข้อมูลพร้อมหน่วย Gigabytes
mysql> insert into DemoTable values('120 Gigabytes');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('190 Gigabytes');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('250 Gigabytes');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('1000 Gigabytes');
Query OK, 1 row affected (0.12 sec)
แสดงข้อมูลก่อนอัปเดต
mysql> select * from DemoTable;
+----------------+ | Download | +----------------+ | 120 Gigabytes | | 190 Gigabytes | | 250 Gigabytes | | 1000 Gigabytes | +----------------+ 4 rows in set (0.00 sec)
คำสั่ง UPDATE ตัดทิ้งข้อความหลังช่องว่าง
mysql> update DemoTable set Download = LEFT(Download, INSTR(Download, ' ') - 1); Query OK, 4 rows affected (0.16 sec) Rows matched: 4 Changed: 4 Warnings: 0
ตรวจสอบข้อมูลหลังอัปเดต (เหลือแค่ตัวเลข)
mysql> select * from DemoTable;
+----------+ | Download | +----------+ | 120 | | 190 | | 250 | | 1000 | +----------+ 4 rows in set (0.00 sec)
คำอธิบายการทำงาน:
INSTR(Download, ' ')หาตำแหน่งช่องว่างแรก (เช่น ตำแหน่ง 4 สำหรับ '120 Gigabytes')- 1ลบ 1 เพื่อไม่รวมช่องว่างเองLEFT(Download, ...)ตัดเอาเฉพาะตัวอักษรซ้ายมือจนถึงตำแหน่งนั้น
วิธีทางเลือก: ใช้ SUBSTRING_INDEX(Download, ' ', 1) ซึ่งสั้นกว่าและอ่านง่ายกว่า (เอาส่วนก่อนช่องว่างตัวแรก)