Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

คิวรี่ MySQL เพิ่มจุดท้ายถ้าข้อความเกิน 10 คำ

สำหรับเรื่องนี้ ใช้คำสั่ง CASE statement ครับ

สร้างตารางตัวอย่าง

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

เพิ่มข้อมูลตัวอย่าง

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)

แสดงข้อมูลทั้งหมด

mysql> select * from DemoTable;

ผลลัพธ์

+--------------------------------------------------------+
| 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)

คำสั่งเพิ่มจุดถ้าข้อความเกิน 10 คำ

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;

ผลลัพธ์

+-------------------------------------------------------------------+
| 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)

คำอธิบาย: SUBSTRING_INDEX(สตริง, delimiter, นับ) - นับคำที่ 10 ถ้าเท่ากับต้นฉบับ (ไม่เกิน 10 คำ) แสดงต้นฉบับ มิฉะนั้น ตัด 10 คำแรกแล้วต่อจุด