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

Thay thế chỉ lần xuất hiện đầu tiên của ký tự trong MySQL

Để tìm và thay thế chỉ lần xuất hiện đầu tiên của một ký tự trong cột, kết hợp CONCAT(), REPLACE(), LEFT(), SUBSTRING() và INSTR().

Cú pháp

UPDATE ten_bang 
SET ten_cot = CONCAT(
    REPLACE(LEFT(ten_cot, INSTR(ten_cot, 'ky_tu_tim')), 'ky_tu_tim', 'ky_tu_thay'),
    SUBSTRING(ten_cot, INSTR(ten_cot, 'ky_tu_tim') + 1)
);

Ví dụ minh họa

Tạo bảng và chèn dữ liệu có lỗi chính tả 'Thks' thay vì 'Thanks':

mysql> CREATE TABLE UserInformation (
    -> UserId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> UserName VARCHAR(10),
    -> UserPost TEXT
    -> );

mysql> INSERT INTO UserInformation(UserName, UserPost) VALUES('Larry', 'Thks is a MySQL query');
mysql> INSERT INTO UserInformation(UserName, UserPost) VALUES('Mike', 'Thks is not a java program');
mysql> INSERT INTO UserInformation(UserName, UserPost) VALUES('Sam', 'Thks is a SQL syntax');

Dữ liệu ban đầu:

+--------+----------+----------------------------+
| UserId | UserName | UserPost                   |
+--------+----------+----------------------------+
|      1 | Larry    | Thks is a MySQL query      |
|      2 | Mike     | Thks is not a java program |
|      3 | Sam      | Thks is a SQL syntax       |
+--------+----------+----------------------------+

Thay thế 'k' đầu tiên thành 'i' (Thks → This):

mysql> UPDATE UserInformation
    -> SET UserPost = CONCAT(
    ->     REPLACE(LEFT(UserPost, INSTR(UserPost, 'k')), 'k', 'i'),
    ->     SUBSTRING(UserPost, INSTR(UserPost, 'k') + 1)
    -> );

Kết quả:

+--------+----------+----------------------------+
| UserId | UserName | UserPost                   |
+--------+----------+----------------------------+
|      1 | Larry    | This is a MySQL query      |
|      2 | Mike     | This is not a java program |
|      3 | Sam      | This is a SQL syntax       |
+--------+----------+----------------------------+

Giải thích: INSTR() tìm vị trí ký tự 'k' đầu tiên. LEFT() lấy phần chuỗi đến vị trí đó, REPLACE() thay đổi ký tự đó, sau đó CONCAT() nối với phần còn lại từ SUBSTRING().