欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

SQL statement to search for Word Boundary_MySQL

程序员文章站 2022-03-16 10:19:32
...
SQL statement to search for Word Boundary_MySQLSQL statement to search for Word Boundary_MySQLSQL statement to search for Word Boundary_MySQLSQL statement to search for Word Boundary_MySQLSQL statement to search for Word Boundary_MySQL

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...