在 MySQL 中搜索文本列内的字符串?
mysqlmysqli database
您可以在 MySQL 中借助 LIKE 子句搜索文本列内的字符串。语法如下 −
select *from yourTableName where yourColumnName like '%anyStringValue%';
要使用上述语法,我们首先创建一个表 −
mysql> create table SearchTextDemo −> ( −> BookName TEXT −> ); Query OK, 0 rows impacted (0.55 sec)
在表中插入一些字符串。查询如下 −
mysql> insert into SearchTextDemo values('Let us C'); Query OK, 1 row affected (0.28 sec) mysql> insert into SearchTextDemo values('C in Depth'); Query OK, 1 row affected (0.14 sec) mysql> insert into SearchTextDemo values('C in Depth with Data Structure'); Query OK, 1 row affected (0.18 sec) mysql> insert into SearchTextDemo values('Introduction to Java'); Query OK, 1 row affected (0.17 sec) mysql> insert into SearchTextDemo values('Java in Depth'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示所有记录,查询如下 −
mysql> select *from SearchTextDemo;
以下是输出 −
+--------------------------------+ | BookName | +--------------------------------+ | Let us C | | C in Depth | | C in Depth with Data Structure | | Introduction to Java | | Java in Depth | +--------------------------------+ 5 rows in set (0.00 sec)
这是在文本列中搜索特定字符串的查询 −
mysql> select *from SearchTextDemo where BookName like '%in Depth%';
以下是输出 −
+--------------------------------+ | BookName | +--------------------------------+ | C in Depth | | C in Depth with Data Structure | | Java in Depth | +--------------------------------+ 3 rows in set (0.00 sec)
查看上面的示例输出,已从列名 ‘BookName’ 中搜索字符串 ‘in Depth’,数据类型为 TEXT。