简体   繁体   中英

mySQL LIKE / MATCH to return more accurate search results

I am trying to build a more accurate search feature for my news section on my website. I use to use LIKE on the content area, however, my problem is that when I search for "three search" when in the database it is written as "three word search" it does not return any content.

I was advised to use MATCH, but I am unable to return ANY results with it. My query returns a variety of fields from multiple tables. My search area has more than 1 search block, which I can change if need be, but I need it to return all results irrespective if they have a low score or not.

Here is my SQL:

$sql = "SELECT news.id, news.name, news.date, news_categories.name as catName, news.author, statuses.name as statusName, MATCH(news.name, news.summary, news.content, news.keywords) AGAINST ('".$content."') AS score FROM news, news_categories, statuses WHERE news.name LIKE '%".$name."%' AND MATCH(news.name, news.summary, news.content, news.keywords) AGAINST ('".$content."') AND news_categories.id LIKE '%".$category."%' AND news.status_id LIKE '%".$status."%' AND news.status_id=statuses.id AND news.category_id=news_categories.id";

Fulltext did not quite help here as my requirements was to always get the values. An easier and more effective way for me was to do a str_replace on the variable containing the search term and replace all " " with an %, so that the term would effectively be "%three%word%search%"

You'll have to create a FULLTEXT index on the fields you wish to search. For example:

ALTER TABLE news
  ADD FULLTEXT(name, summary, content, keywords);

Now, you may use those fields in a MATCH() ... AGAINST clause your query. Read the MySQL documentation on fulltext searching for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM