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

การอัปเดตค่าด้วย Substring ตัดส่วนหลัง Separator ใน MySQL

ใช้ SUBSTRING_INDEX() เพื่อตัดส่วนหลัง Separator (เช่น /) แล้วอัปเดตค่ากลับเข้าไป

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

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

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

mysql> insert into DemoTable values('John/56989'); Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('David/74674'); Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('Bob/45565'); Query OK, 1 row affected (0.09 sec)

แสดงข้อมูลก่อนอัปเดต

mysql> select *from DemoTable;
+-------------+
| StudentName |
+-------------+
| John/56989  |
| Carol       |
| David/74674 |
| Bob/45565   |
+-------------+
4 rows in set (0.00 sec)

คิวรี่อัปเดต ตัดส่วนหลัง / ออก

mysql> update DemoTable set StudentName=substring_index(StudentName,'/',1); 
Query OK, 3 rows affected (0.13 sec)
Rows matched: 4  Changed: 3  Warnings: 0

ตรวจสอบผลลัพธ์

mysql> select *from DemoTable;
+-------------+
| StudentName |
+-------------+
| John        |
| Carol       |
| David       |
| Bob         |
+-------------+
4 rows in set (0.00 sec)

คำอธิบาย SUBSTRING_INDEX

  • SUBSTRING_INDEX(str, delim, count)
  • count = 1 ส่วนซ้ายสุด (ก่อน delimiter ตัวแรก)
  • count = -1 ส่วนขวาสุด (หลัง delimiter ตัวสุดท้าย)
  • หา delimiter ไม่เจอ → คืนค่าสตริงทั้งหมด (Carol ไม่มี / → คงเดิม)

ทดสอบก่อน UPDATE (Best Practice)

SELECT StudentName, SUBSTRING_INDEX(StudentName, '/', 1) as new_name
FROM DemoTable;

วิธีทางเลือกอื่น

  • LEFT(StudentName, LOCATE('/', StudentName) - 1) - แต่ต้องจัดการกรณีไม่มี / (LOCATE คืน 0)
  • SUBSTRING(StudentName, 1, INSTR(StudentName, '/') - 1) - คล้ายกัน
  • REGEXP_REPLACE(StudentName, '/.*$', '') - MySQL 8.0+

Generated Column (MySQL 5.7+) - แนวทางที่ดีกว่า

ALTER TABLE DemoTable 
ADD clean_name VARCHAR(100) 
GENERATED ALWAYS AS (SUBSTRING_INDEX(StudentName, '/', 1)) STORED;

แล้ว Query ที่ clean_name แทน (ใช้ Index ได้)