Computer >> Máy Tính >  >> Lập trình >> MySQL

MySQL String Last Index Of trong một URL?

Để lấy chỉ mục cuối cùng, hãy sử dụng hàm SUBSTRING_INDEX () từ MySQL. Cú pháp như sau -

SELECT yourColumnName1,...N,SUBSTRING_INDEX(yourColumnName,’yourDelimiter’,-1)as anyVariableName from yourTableName;

Để hiểu cú pháp trên, chúng ta hãy tạo một bảng. Truy vấn để tạo bảng như sau

mysql> create table LastIndexString
   -> (
   -> Id int,
   -> yourURL text
   -> );
Query OK, 0 rows affected (0.89 sec)

Chèn một số bản ghi trong bảng bằng lệnh INSERT. Truy vấn như sau -

mysql> insert into LastIndexString values(1,'https −//www.example.com/home.html');
Query OK, 1 row affected (0.26 sec)

mysql> insert into LastIndexString values(2,'https −//exampledemo.example.com/index.jsp');
Query OK, 1 row affected (0.18 sec)

mysql> insert into LastIndexString values(3,'https −//www.example.com/question/LastString');
Query OK, 1 row affected (0.18 sec)

Hiển thị tất cả các bản ghi từ bảng bằng cách sử dụng câu lệnh SELECT. Truy vấn như sau -

mysql> select *from LastIndexString;

Sau đây là kết quả hiển thị chuỗi URL -

+------+---------------------------------------------+
| Id   | yourURL                                     |
+------+---------------------------------------------+
| 1    | https −//www.example.com/home.html          |
| 2    | https −//exampledemo.example.com/index.jsp  |
| 3    | https −//www.example.com/question/LastString|
+------+---------------------------------------------+
3 rows in set (0.00 sec)

Đây là truy vấn để lấy chuỗi chỉ mục cuối cùng từ chuỗi URL -

mysql> select Id, substring_index(yourURL,'/',-1) as LastStringFromURL from LastIndexString;

Sau đây là đầu ra hiển thị một phần của URL -

+------+-------------------+
| Id   | LastStringFromURL |
+------+-------------------+
|    1 | home.html         |
|    2 | index.jsp         |
|    3 | LastString        |
+------+-------------------+
3 rows in set (0.00 sec)