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

ดึงส่วนท้ายของ URL ใน MySQL ด้วย SUBSTRING_INDEX()

ใช้ SUBSTRING_INDEX(str, delim, -1) ดึงส่วนหลังตัวแบ่งตัวสุดท้าย (Last Index) รูปแบบ:

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

ตัวอย่าง: ดึงชื่อไฟล์จาก URL

สร้างตาราง URL:

mysql> CREATE TABLE LastIndexString (Id INT, yourURL TEXT);
mysql> INSERT INTO LastIndexString VALUES
    -> (1, 'https://www.example.com/home.html'),
    -> (2, 'https://exampledemo.example.com/index.jsp'),
    -> (3, 'https://www.example.com/question/LastString');

ดึงส่วนท้ายหลัง / ตัวสุดท้าย

mysql> SELECT Id, SUBSTRING_INDEX(yourURL, '/', -1) AS LastStringFromURL FROM LastIndexString;

ผลลัพธ์:

+------+-------------------+
| Id   | LastStringFromURL |
+------+-------------------+
| 1    | home.html         |
| 2    | index.jsp         |
| 3    | LastString        |
+------+-------------------+

ประยุกต์: ดึงชื่อไฟล์, slug, หรือ ID จาก URL/Path ได้ง่ายโดยไม่ต้องใช้ REGEXP