Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Trích xuất chuỗi con từ chuỗi phân tách bằng dấu gạch chéo trong MySQL với SUBSTRING_INDEX

Tạo bảng mã sinh viên

mysql> CREATE TABLE DemoTable1416 (StudentCode VARCHAR(100));
INSERT INTO DemoTable1416 VALUES
('101/John/Smith'),('901/Carol/Taylor'),('400/David/Miller');

Dữ liệu

mysql> SELECT * FROM DemoTable1416;
+------------------+
| StudentCode      |
+------------------+
| 101/John/Smith   |
| 901/Carol/Taylor |
| 400/David/Miller |
+------------------+

Truy vấn: SUBSTRING_INDEX(StudentCode, '/', -2) lấy 2 phần cuối

mysql> SELECT SUBSTRING_INDEX(StudentCode, '/', -2) FROM DemoTable1416;

Kết quả: Tên/Họ (bỏ phần ID đầu)

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

Giải thích: SUBSTRING_INDEX(str, delim, count): count > 0 lấy từ trái, count < 0 lấy từ phải (|count| phần). -2 lấy 2 phần cuối sau dấu '/'.