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

MySQL: ดึง Substring จากสตริงคั่น Slash ด้วย SUBSTRING_INDEX

การใช้ SUBSTRING_INDEX() แยกส่วนสตริงที่คั่นด้วย Delimiter (Slash)

SUBSTRING_INDEX(str, delim, count) คืนค่าสตริงก่อน delimiter ตัวที่ count (ถ้า count > 0) หรือหลัง delimiter ตัวที่ |count| (ถ้า count < 0)

สร้างตารางและข้อมูล

mysql> create table DemoTable1416 (
    -> StudentCode varchar(100)
    -> );
Query OK, 0 rows affected (1.56 sec)

mysql> insert into DemoTable1416 values('101/John/Smith');
mysql> insert into DemoTable1416 values('901/Carol/Taylor');
mysql> insert into DemoTable1416 values('400/David/Miller');

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

+------------------+
| StudentCode      |
+------------------+
| 101/John/Smith   |
| 901/Carol/Taylor |
| 400/David/Miller |
+------------------+

คำสั่ง SUBSTRING_INDEX(StudentCode, '/', -2)

mysql> select substring_index(StudentCode, '/', -2) from DemoTable1416;

ผลลัพธ์ (ส่วนหลัง slash ตัวแรก: Name/Surname)

+-------------------------------------+
| substring_index(StudentCode, '/', -2) |
+-------------------------------------+
| John/Smith                            |
| Carol/Taylor                          |
| David/Miller                          |
+-------------------------------------+

อธิบาย count = -2

  • นับ slash จากขวาไปซ้าย 2 ตัว
  • คืนค่าส่วนหลัง slash ตัวที่ 2 จากขวา (คือ ทุกอย่างหลัง slash ตัวแรก)
  • รูปแบบ: ID/Name/Surname → ต้องการ Name/Surname

ตาราง count ต่างๆ (สำหรับ '101/John/Smith')

countผลลัพธ์คำอธิบาย
1101ก่อน slash ตัวแรก
2101/Johnก่อน slash ตัวที่ 2
-1Smithหลัง slash ตัวสุดท้าย
-2John/Smithหลัง slash ตัวที่ 2 จากขวา
-3101/John/Smithหลัง slash ตัวที่ 3 จากขวา (ทั้งสตริง)

กรณี Delimiter ไม่มีในสตริง

  • count > 0: คืนสตริงทั้งหมด
  • count < 0: คืนสตริงว่าง ('')

MySQL 8.0+: REGEXP_SUBSTR (ยืดหยุ่นกว่า)

-- ดึงส่วนแรก (ID)
REGEXP_SUBSTR(StudentCode, '^[^/]+')

-- ดึงส่วนกลาง (Name)
REGEXP_SUBSTR(StudentCode, '(?<=/)[^/]+(?=/)')

-- ดึงส่วนหลัง (Surname)
REGEXP_SUBSTR(StudentCode, '[^/]+$')

สรุป: SUBSTRING_INDEX เร็ว สะดวก สำหรับ delimiter-based format — ใช้ count ลบ เพื่อดึง "ส่วนท้าย" ได้ง่าย