4

I am currently working on a search feature for a website that searches through a database for a specific animal.

Say the user inputs rabbit, the search will go through the db and display the results for rabbit.

Now say a user inputs bunny the search will go through the db but will not find a match for bunny.

Most people know that bunny means rabbit, but the database doesn't know that. At this point I have implemented a MySQL thesaurus within the same database to search for synonyms of what the user inputs.

This means that if the user inputs bunny it will display a list of synonyms for bunny.

In that list there is the word Rabbit and I am trying to pull that word out of there to generate a match. At this point I have the following.

"SELECT  `engname` FROM  `searchtestdb` WHERE  `engname` IS NOT NULL  ";

-- This displays the english name of every animal within that table. --

"SELECT synonyms.* FROM words LEFT JOIN synonyms ON synonyms.word_id = words.word_id WHERE word = \"$searchBox\""

-- This displays the synonyms for $searchBox which is the word the user inputs. --

Both of these queries display what I want them to display. In other words, the first query gives me all of the animals names in the table, and the second query gives me the synonyms for the word the user inputed.

At this point my problem is how to compare the synonyms to all the animals names. I've tried several queries with the LIKE command but I keep getting syntax errors.

Is what I am asking possible? If not what would be a better course of action? Any help would be greatly appreciated.

Thank You.

I got a semi fiddle going for y'all.

http://sqlfiddle.com/#!2/47d42/3

It only works for "bunny" since the entire synonym and word list is too big for fiddle.

4

2 回答 2

1
select * from searchtestdb
where engname in 
(
  SELECT synonyms.synonym 
  FROM words 
  LEFT JOIN synonyms ON synonyms.word_id = words.word_id 
  WHERE word = "bunny"
)  

SQLFIddle

EDIT: Since you probably also want to search for word directly inputted and not just it's synonyms, you should also add that condition:

OR engname = "bunny"

SQLFIddle

于 2013-04-19T08:07:58.733 回答
0

I think the idea is this: (pseudocoded)

Create a function which returns true or false (with a parameter as the search word) of whether there exists a result. This is a basic

SELECT COUNT > 0 FROM table WHERE text LIKE %parameter%

Now create a function that returns a table of results:

  • loop through the the synonyms of the word which again comes as a parameter to this function
  • add to table of the results if a synonym in a loop fits the function above.
  • return the table
于 2013-04-19T07:06:22.963 回答