I have a form with an input box where the user can specify their names, the names may be two or more words, eg John Smith or John Michael Smith.
I have to write a query that returns records containing all words in the name presented. So query will return records that has the name of all those words, but may have different order.
For example, if the search string is John Michael Smith, the query should be able to return records with names like Michael John Smith, Michael Smith John, John Smith Michael or some combination of all these words there. As can be seen only return records that still has all the words in the name field, but may have different order. However, it should return results that do not contain part of the name, for example, John Michael should not be returned because it does not have Smith in there.
I tried query like this:
SELECT id, name FROM users WHERE
name LIKE '%Michael%' &&
name LIKE '%Smith%' &&
name LIKE '%John%'
The same problem happens with:
SELECT * FROM users WHERE MATCH (name)
AGAINST ('+Michael +Smith +John' IN BOOLEAN MODE);
Both queries also returns John Michael instead of records that contain all three words 🙁
I can not figure out how to write a query to the requirement so that I have. Please help.
Use a fulltext index. That’s the easiest/quickest method. Otherwise you’re stuck parseing your search string, converting
into
which very quickly gets painful to do, and VERY slow to perform, as
LIKE %..%searches cannot use indexes.Note that Fulltext indexes are currently restricted to MyISAM tables, so if you’re on InnoDB, you’ll have to use workarounds (parallel tables in MyISAM format to hold the searchable data with triggers to keep the two copies synchronized). Apparently Fulltext for InnoDB is FINALLY in the development pipeline, but it’s not here yet.