如果字串超過 10 個字,MySQL 查詢如何新增點號?


為此,請使用 CASE 語句。讓我們首先建立一個表 -

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

使用 insert 命令在表中插入一些記錄 -

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)

使用 select 語句從表中顯示所有記錄 -

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)

更新日期: 2020 年 6 月 30 日

290 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告