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

Truy vấn MySQL thêm dấu ba chấm nếu chuỗi vượt quá 10 từ

Sử dụng câu lệnh CASE kết hợp SUBSTRING_INDEX().

Tạo bảng demo

mysql> create table DemoTable (
    -> Title text
    -> );
Query OK, 0 rows affected (0.61 sec)

Chèn dữ liệu

mysql> insert into DemoTable values('My name is John and this is my first tutorial on MySQL');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('This is Carol and I work on MongoDB');
Query OK, 1 row affected (0.19 sec)

Hiển thị dữ liệu

mysql> select * from DemoTable;

Kết quả

+--------------------------------------------------------+
| Title                                                  |
+--------------------------------------------------------+
| My name is John and this is my first tutorial on MySQL |
| This is Carol and I work on MongoDB                    |
+--------------------------------------------------------+
2 rows in set (0.00 sec)

Truy vấn thêm "...................." nếu vượt quá 10 từ

mysql> select (case when substring_index(tbl.Title, ' ', 10) = tbl.Title 
    -> then tbl.Title 
    -> else concat(substring_index(tbl.Title, ' ', 10), '....................') 
    -> end) AS AddDots 
    -> from DemoTable tbl;

Kết quả

+-------------------------------------------------------------------+
| AddDots                                                           |
+-------------------------------------------------------------------+
| My name is John and this is my first tutorial.................... |
| This is Carol and I work on MongoDB                               |
+-------------------------------------------------------------------+
2 rows in set (0.00 sec)

Giải thích:

  • SUBSTRING_INDEX(str, delim, count): Lấy phần chuỗi trước lần xuất hiện thứ count của delim. Với count=10, delim=' ', lấy 10 từ đầu.
  • So sánh với chuỗi gốc: nếu bằng nhau → ít hơn hoặc bằng 10 từ → giữ nguyên.
  • Nếu khác → nhiều hơn 10 từ → lấy 10 từ đầu + nối dấu ba chấm.

Cải tiến: Dùng TRIM() để loại bỏ khoảng trắng thừa, hoặc tính toán độ dài động thay vì cố định 20 dấu chấm.