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

Lấy chuỗi con từ ký tự thứ 20 trở đi trong MySQL với SUBSTRING


Giới thiệu

Dùng SUBSTRING(str FROM pos) (cú pháp chuẩn SQL) hoặc SUBSTRING(str, pos) để lấy chuỗi con từ vị trí pos đến hết chuỗi. Vị trí tính từ 1.

Ví dụ minh họa

Tạo bảng và chèn dữ liệu

mysql> CREATE TABLE DemoTable (Title TEXT);
mysql> INSERT INTO DemoTable VALUES 
('C is a good programming language to start'),
('Java is good with data structure and algorithm'),
('Coding is very important');

Truy vấn lấy từ ký tự 20

mysql> SELECT SUBSTRING(Title FROM 20) FROM DemoTable;

Kết quả

+-----------------------------+
| SUBSTRING(Title FROM 20)    |
+-----------------------------+
| ming language to start      |
| ata structure and algorithm |
| rtant                       |
+-----------------------------+

Giải thích

  • Dòng 1: 'C is a good programming language to start' → ký tự 20 là 'm' của 'ming...'.
  • Dòng 2: 'Java is good with data structure and algorithm' → ký tự 20 là 'a' của 'ata...'.
  • Dòng 3: 'Coding is very important' → độ dài < 20? Thực tế dài hơn, ký tự 20 là 'r' của 'rtant'.

Các cú pháp SUBSTRING

Cú phápÝ nghĩa
SUBSTRING(str, pos)Từ pos đến hết
SUBSTRING(str FROM pos)Chuẩn SQL, từ pos đến hết
SUBSTRING(str, pos, len)Từ pos, độ dài len
SUBSTRING(str FROM pos FOR len)Chuẩn SQL, từ pos, độ dài len

Lưu ý Unicode

MySQL 8.0+ tính vị trí theo **ký tự (character)**, không phải byte. An toàn cho UTF-8 (tiếng Việt, emoji...).