首页  >  文章  >  数据库  >  SQL statement to search for Word Boundary_MySQL

SQL statement to search for Word Boundary_MySQL

WBOY
WBOY原创
2016-05-31 08:48:011000浏览
Facebook Twitter Google+ SQL statement to search for Word Boundary_MySQL Pretty Print

Send this article by email

What is your name?

Please indicate below the emails to which you want to send this article: SQL statement to search for Word Boundary

Enter one email per line. No more than 5 emails.

In SQL, sometimes, you want to search a string field that contains a key, but as a whole word. So for example, if you search for ‘ word ‘, you do not want ‘ wordword ‘ to be included in the result. Suppose, we have the following data in the MySQL table  test.

mysql> select * from test;+-------------------+| name|+-------------------+| word|| word ok || ok word || wordword|| wordword wordword || (word)(word)|| ,word,|+-------------------+7 rows in set (0.00 sec)
mysql> select * from test;+-------------------+| name|+-------------------+| word|| word ok || ok word || wordword|| wordword wordword || (word)(word)|| ,word,|+-------------------+7 rows in set (0.00 sec)

So, if we use percentage symbol % to match one or a few characters, we can use like “%word%” to match, but this gives unnecessary matches.

mysql> select * from test where name like "%word%";+-------------------+| name|+-------------------+| word|| word ok || ok word || wordword| ---------------> incorrect match| wordword wordword | ---------------> incorrect match| (word)(word)|| ,word,|+-------------------+7 rows in set (0.00 sec)
mysql> select * from test where name like "%word%";+-------------------+| name|+-------------------+| word|| word ok || ok word || wordword| ---------------> incorrect match| wordword wordword | ---------------> incorrect match| (word)(word)|| ,word,|+-------------------+7 rows in set (0.00 sec)

The correct method is to use the REGEXP and the [[:<: and>:]] word-boundary markers:

mysql> select * from test where name regexp '[[:<:>:]]';+--------------+| name |+--------------+| word || word ok|| ok word|| (word)(word) || ,word, |+--------------+5 rows in set (0.01 sec)</:>
mysql> select * from test where name regexp '[[:<:>:]]';+--------------+| name |+--------------+| word || word ok|| ok word|| (word)(word) || ,word, |+--------------+5 rows in set (0.01 sec)</:>

–EOF–

GD Star Rating

loading...

GD Star Rating

loading...

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn