Currently, I am doing a search function. Lets say in my database, I have this data:
- Keyword1
- Keyword2
- Keyword3
- Keysomething
- Key
and the user entered: “Key” as the keyword to search. This is my current query:
SELECT * FROM data WHERE (
data_string LIKE '$key%' OR
data_string LIKE '%$key%' OR
data_string LIKE '%$key'
)
Basically, I have 2 questions:
-
How do I sort by (order by) similarity. From above example, I wanted “Key” as my first result. My current result is: Keyword1, Keyword2, Keyword3, Keysomething and Key
-
My SQL query only search by the “data_string” column, what if I want to seach others column? Do I need to do something like this:
SELECT * FROM data WHERE (
data_string LIKE '$key%' OR
data_string LIKE '%$key%' OR
data_string LIKE '%$key'
) OR (
data_other LIKE '$key%' OR
data_other LIKE '%$key%' OR
data_other LIKE '%$key'
) -- ...
Is there any better/faster query than Q2?
I am not sure if
LIKEis the right way to do this. If you need to search inside your text for keywords and sort results by relevancy score, you should use MySQL Full-Text index and MySQL Full-text Search functions. Sorry if this leads you away from what you are actually trying to do but I do recommend having one look at it. Some quotes from MySQL reference manual:1) How to create full text index on multiple columns of a table
2) Sample data
3) Sample query that searches multiple columns for keywords and displays result + the score: