在 MySQL 中搜索分隔符之间的文本?


你需要将 LOCATE() 与 SUBSTR() 结合使用。以下语法将会找到分隔符后的单词。此处,分隔符是冒号 (:),你可以使用另一个分隔符,即由你决定。语法如下 −

SELECT
   SUBSTR(yourColumnName,
      LOCATE(':',yourColumnName)+1,
         (CHAR_LENGTH(yourColumnName) - LOCATE(':',REVERSE(yourColumnName)) - LOCATE(':',yourColumnName))) AS anyAliasName
FROM yourTableName;

为了理解以上语法,让我们创建一个表。创建表的查询如下 −

mysql> create table SearchTextBetweenDelimitersDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Words longtext,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.67 sec)

现在,你可以使用插入命令在表中插入一些记录。查询如下 −

mysql> insert into SearchTextBetweenDelimitersDemo(Words) values('Object:Oriented:Programming');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SearchTextBetweenDelimitersDemo(Words) values('C++:Java:C#');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SearchTextBetweenDelimitersDemo(Words) values('SQLServer:MySQL:Oracle');
Query OK, 1 row affected (0.17 sec)
mysql> insert into SearchTextBetweenDelimitersDemo(Words) values('SQL SQLServer:MySQL:Oracle');
Query OK, 1 row affected (0.18 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from SearchTextBetweenDelimitersDemo;

以下是输出 −

+----+-----------------------------+
| Id | Words                       |
+----+-----------------------------+
|  1 | Object:Oriented:Programming |
|  2 | C++:Java:C#                 |
|  3 | SQLServer:MySQL:Oracle      |
|  4 | SQL SQLServer:MySQL:Oracle  |
+----+-----------------------------+
4 rows in set (0.00 sec)

以下是搜索和显示分隔符之间的单词的查询 −

mysql> SELECT
   -> SUBSTR(Words,
   -> LOCATE(':',Words)+1,
   -> (CHAR_LENGTH(Words) - LOCATE(':',REVERSE(Words)) - LOCATE(':',Words))) AS Text
   -> FROM SearchTextBetweenDelimitersDemo;

以下是输出 −

+----------+
| Text     |
+----------+
| Oriented |
| Java     |
| MySQL    |
| MySQL    |
+----------+
4 rows in set (0.00 sec)

更新于: 2019-07-30

494 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告