I have a requirement to add a search feature to a site I'm building and was wondering if anyone has done something similar.
I have a sample table that contains the details of cats in this format:
Name, place, type, age, gender and size.
And I only have one search box where users can enter their search terms. My question is, ho开发者_如何学Gow do I search the table if, for example someone types in "cat in Paris"? I want to be able to search all the fields and return a something if found.
Is there any way to achieve this rather than having lots of boxes for them to select a search criteria? Any help or suggestion would be appreciated.
One of the simpler approaches that works very well in this situation is to do a fulltext search in mysql. You can have it index all of the columns and to a natural language search.
If you had a mysql table called cats with the following schema:
mysql> desc cats;
+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(100) | YES | MUL | NULL | |
| place | varchar(100) | YES | | NULL | |
| type | varchar(100) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
| gender | varchar(100) | YES | | NULL | |
| size | varchar(100) | YES | | NULL | |
+--------+--------------+------+-----+---------+----------------+
You can run the following SQL to create the index:
CREATE FULLTEXT INDEX cats_search ON cats (name, type, place, gender);
Then when you get the search string 'male tabby in paris' you can search the table with this SQL:
SELECT *
, MATCH(name, type, place, gender)
AGAINST ('male tabby in paris' IN BOOLEAN MODE) relevance
FROM cats
WHERE MATCH(name, type, place, gender)
AGAINST ('male tabby in paris' IN BOOLEAN MODE)
ORDER BY relevance DESC;
will return all of the rows that match those terms in the order mysql decides is most relevant.
You will have to research mysql fulltext searches to fine tune the results they way you want, but this should get you off the ground.
精彩评论