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

ดึงข้อความหลัง Slash สุดท้ายใน MySQL

ใช้ SUBSTRING_INDEX() ด้วยตัวนับลบ เพื่อดึงข้อความหลังเครื่องหมาย slash (/) ตัวสุดท้าย

รูปแบบคำสั่ง

SELECT SUBSTRING_INDEX(yourColumnName, '/', -1) AS text_after_last_slash FROM yourTableName;

ตัวอย่าง

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

mysql> create table selectTextAfterLastSlashDemo (
    -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> UserPathDirectory varchar(200)
    -> );

mysql> insert into selectTextAfterLastSlashDemo(UserPathDirectory) values
    -> ('C:/MyFolder1/MyEntityFramework'),
    -> ('D:/MySpringFrameworkDemo'),
    -> ('E:/Java/MyRootFolder/Source/AllHibernateDemo'),
    -> ('C:/Program Files/MySQL/Server 8.0'),
    -> ('C:/John/Folder1/Folder2');

2. ดึงข้อความหลัง Slash สุดท้าย

mysql> select substring_index(UserPathDirectory,'/','-1') as TextAfterLastSlash 
    -> from selectTextAfterLastSlashDemo;
+-----------------------+
| TextAfterLastSlash    |
+-----------------------+
| MyEntityFramework     |
| MySpringFrameworkDemo |
| AllHibernateDemo      |
| Server 8.0            |
| Folder2               |
+-----------------------+

การทำงานของ SUBSTRING_INDEX(str, delim, count)

  • count = -1: ส่วนขวาสุดท้ายหลัง delimiter ตัวสุดท้าย
  • count = -2: ส่วนขวาจาก delimiter ตัวที่ 2 จากท้าย

กรณีพิเศษ

รองรับ Backslash (Windows Path)

SELECT SUBSTRING_INDEX(REPLACE(path, '\\', '/'), '/', -1) FROM table;

ดึงชื่อโฟลเดอร์แม่ (Parent Folder)

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(path, '/', -2), '/', 1) as parent_folder
FROM selectTextAfterLastSlashDemo;
Pathผลลัพธ์หมายเหตุ
C:/folder/file.txtfile.txtปกติ
C:/folder/(ว่าง)จบด้วย slash
C:/folderfolderไม่มี slash ท้าย
/etc/nginx/nginx.confnginx.confLinux path