4

我有一个带有关键字搜索的 PHP 界面,处理一个具有关键字字段的 DB(MySQL)。

关键字字段的设置方式如下,它是一个varchar,所有单词的格式如下图...

the, there, theyre, their,thermal 等...

如果我只想从搜索中返回确切的单词“the”,这将如何实现?

我曾尝试在 PHP 中使用'the%'and '%the',但它无法通过不返回关键字出现的所有行来工作。

有没有更好(更准确)的方法来解决这个问题?

谢谢

4

5 回答 5

1

如果要选择恰好具有关键字的行the

SELECT * FROM table WHERE 关键字='the'

如果要选择其中the 任何位置包含关键字的行:

SELECT * FROM table WHERE 关键字 LIKE '%the%'

如果要选择以关键字开头the的行:

SELECT * FROM table WHERE 关键字 LIKE 'the%'

如果要选择以关键字结尾the的行:

SELECT * FROM table WHERE 关键字 LIKE '%the'

于 2012-11-05T16:39:26.553 回答
1

试试这个

SELECT * FROM tablename
  WHERE fieldname REGEXP '[[:<:]]test[[:>:]]'

[[:<:]]并且[[:>:]]是单词边界的标记。

MySQL 正则表达式

于 2012-11-05T16:39:46.343 回答
1

如果您还搜索逗号,则可以确定您得到了整个单词。

where keywordField like '%, the, %'
   or keywordField like '%, the'
   or keywordField like 'the, %'
于 2012-11-05T16:40:07.693 回答
0

也许我没有正确理解这个问题......但是如果你想要所有出现“the”的单词,那么 LIKE '%word%' 应该可以工作。

If the DB of words is HUGE MySQL may fail to retrieve some of the words, that can be solved in 2 ways...

1- get a DB that support bigger sizes (not many ppl would chose this one tho). For example SQL Server has a 'CONTAINS' function that works better than LIKE '%word%'.

2- use a external search tool that uses inverted index search. I used Sphinx for a project and it works quite good. This is better if you rarely UPDATE the rows of the data you want to search from, which should be the case. Sphinx for example would generate a file from your MySQL table and use this file to solve the search (it's very fast), this file should be re-indexed everytime you do a insert or update on the table, making it a much better solution if you rarely update or insert new rows.

于 2012-11-05T16:40:59.783 回答
0

It looks like you have a one to many relationship going on within a column. It might be better to create a separate table for keywords with a row for each keyword and a foreign key to whatever it is you're searching on.

Doing like '%???%' is generally a bad idea because the DB can't make use of an index so it will scan the whole table. Whether this matters will depend on the size of data you're working with but its worth considering up front. The single best way to help DB performance is in the initial table design. This can be tricky to change later.

于 2012-11-05T16:51:51.497 回答