I have an online search box that needs to look across many MySQL columns for a match. And it needs to handle a multi-keyword search.
Use cases:
- I search for DP/101/R/23 (rego no)
- I search for Johnty Winebottom (owner)
- I search for Le Mans 1969 (mixed, history related keywords)
I get a lot of special chars so fulltext doesn't always work. So I'm splitting the keyword input apart on spaces and then looping thorugh and doing LIKE queries.
Simplified query that gets the point across (I've removed many columns):
SELECT `cars`.`id`,
`cars`.`car_id`,
`cars`.`date_of_build`,
…..
FROM (`cars`)
WHERE (
`chassis_no` LIKE "DP/101/R/23"
OR `chassis_no` LIKE "DP/101/R/23 %"
OR `chassis_no` LIKE "% DP/101/R/23"
OR `chassis_no` LIKE "% DP/101/R/23 %"
OR `history` LIKE "DP/101/R/23"
OR `history` LIKE "DP/101/R/23 %"
OR `history` LIKE "% DP/101/R/23"
OR `history` LIKE "% DP/101/R/23 %"
….
In this case (rego no) it's exact so matches the LIKE without spaces on either side.
This works.. but is slow and feels wrong. Is there another way to do this that's more efficient?
EDIT:: Using REGEXP appears to work and actually is a little faster:
chassis_no` REGEXP "([ ]*)DP/101/R/23([ ]*)"
I'm not sure of a better way since fulltext fails on many of the special characters in my data.