在mysql中搜索特定单词

时间:2015-03-19 10:39:43

标签: php mysql regex

我在mysql Db中有String,如下所示

"Good Mayer Brown Corporate & Securities"
"Three Mayer Brown Good & Securities"
"Three Mayer Brown Corporate & Good"
"Three Mayer Brown Goodies & Securities"

我需要找到与LIKE %%关键字不同的确切字词。这是一个例子,

我需要使用"Good"关键字选择行。这将选择前3行。最后一个有额外的单词,如"ies"这是我的预期结果

    "Good Mayer Brown Corporate & Securities"
    "Three Mayer Brown Good & Securities"
    "Three Mayer Brown Corporate & Good" 

我已经尝试过以下查询。

SELECT * FROM table WHERE myword LIKE '% Good %'  OR myword LIKE 'Good%' OR myword LIKE '% Good'

但这不适合我。

2 个答案:

答案 0 :(得分:2)

SELECT * FROM table WHERE myword REGEXP '^.*GOOD.*$

您可以使用REGEXP执行此操作。或者

SELECT * FROM table WHERE myword REGEXP '[[:<:]]GOOD[[:>:]]'

word boundary一起使用。请参阅演示。 http://www.sqlfiddle.com/#!9/e1b9d/6/0

答案 1 :(得分:1)

为什么不使用 Full Text Search ,这是针对这种搜索的优化方式,具有大量功能,而不是像野外卡一样慢,甚至使用索引列使用%%不会影响索引。如果您不知道如何操作,请参阅手册。以下是您的示例

mysql> create table test (search varchar(200),fulltext key(search)) engine=myisam;
Query OK, 0 rows affected (0.08 sec)

mysql> insert into test values ('Good Mayer Brown Corporate & Securities'),('Three Mayer Brown Good & Securities'),('Three Mayer Brown Corporate & Good'),('Three Mayer Brown Goodies & Securities');
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from test where match(search) against ('good' in boolean mode); 
+-----------------------------------------+
| search                                  |
+-----------------------------------------+
| Good Mayer Brown Corporate & Securities |
| Three Mayer Brown Good & Securities     |
| Three Mayer Brown Corporate & Good      |
+-----------------------------------------+
3 rows in set (0.00 sec)