MySQL 查询如果字符串包含超过 10 个单词则添加点?

mysqlmysqli database

为此,使用 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)

相关文章