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

Cách chỉ thay thế lần xuất hiện đầu tiên của một giá trị trong chuỗi MySQL

Sử dụng hàm REGEXP_REPLACE(). Giả sử chuỗi gốc:

This is my first MySQL query. This is the first tutorial. I am learning for the first time.

Cần thay thế chỉ lần xuất hiện đầu tiên của từ "first" thành "second". Kết quả mong đợi:

This is my second MySQL query. This is the first tutorial. I am learning for the first time.

Tạo bảng demo26:

mysql> CREATE TABLE demo26 (
    -> value TEXT
    -> );

Chèn dữ liệu:

mysql> INSERT INTO demo26 VALUES('This is my first MySQL query. This is the first tutorial. I am learning for the first time.');

Hiển thị dữ liệu:

mysql> SELECT * FROM demo26;

Thực hiện cập nhật chỉ thay thế lần đầu tiên (tham số thứ 4 là vị trí bắt đầu, tham số thứ 5 là số lần thay thế):

mysql> UPDATE demo26
    -> SET value = REGEXP_REPLACE(value, 'first', 'second', 1, 1);

Kết quả sau cập nhật:

mysql> SELECT * FROM demo26;
+----------------------------------------------------------------------------------------------+
| value                                                                                        |
+----------------------------------------------------------------------------------------------+
| This is my second MySQL query. This is the first tutorial. I am learning for the first time. |
+----------------------------------------------------------------------------------------------+