首頁  >  文章  >  資料庫  >  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