SQL喜欢附加字符

时间:2016-03-20 14:27:15

标签: mysql sql

我在MySql表上进行文本搜索,我希望找到可能以某些字符结尾的单词。

这是一个例子。搜索单词clip。我希望我的查询能够找到单词clip,clip?,而不是单词clipping

到目前为止,这是我尝试过的:

select * from product where title like '%clip%'

也会找到单词clipping,这是不好的。

select * from product where title like '% clip %'

找不到clipping,但如果后面有逗号clip,也会忽略单词clip,,这对我也不利。

有没有办法指定查询会忽略字母,但包含,.?等字符,或基本上我选择的任何其他字符?

2 个答案:

答案 0 :(得分:3)

您可以使用与单词边界匹配的正则表达式:

... where title regexp '[[:<:]]clip[[:>:]]'

如果您有大量数据并发现自己正在进行大量此类搜索,那么创建full text index然后使用match...against可能是个好主意:

... where match(title) against ('clip');

答案 1 :(得分:2)

使用REGEXP

where title REGEXP '.* clip[,.? ].*'

以下是演示。

mysql> select 'the paper clip is white' REGEXP '.* clip[,.? ].*';
+----------------------------------------------------+
| 'the paper clip is white' REGEXP '.* clip[,.? ].*' |
+----------------------------------------------------+
|                                                  1 |
+----------------------------------------------------+
1 row in set (0.00 sec)

mysql> select 'the paper clip? is white' REGEXP '.* clip[,.? ].*';
+-----------------------------------------------------+
| 'the paper clip? is white' REGEXP '.* clip[,.? ].*' |
+-----------------------------------------------------+
|                                                   1 |
+-----------------------------------------------------+
1 row in set (0.00 sec)

mysql> select 'the paper clipping is white' REGEXP '.* clip[,.? ].*';
+--------------------------------------------------------+
| 'the paper clipping is white' REGEXP '.* clip[,.? ].*' |
+--------------------------------------------------------+
|                                                      0 |
+--------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select 'the paper clipis white' REGEXP '.* clip[,.? ].*';
+---------------------------------------------------+
| 'the paper clipis white' REGEXP '.* clip[,.? ].*' |
+---------------------------------------------------+
|                                                 0 |
+---------------------------------------------------+
1 row in set (0.00 sec)