I have a table which has companies (id, name). Before I had to search the input query against records which was handled with "like". Sometime client wanted it to end with the input query sometime it could occur in between sometime it should start with it. So I used different variation of "like"
Input Query: Micro
select * from Company where CompanyName like "Micro%";
select * from Company where CompanyName like "%Micro%";
select * from Company where CompanyName like "%Micro";
Pretty simple right. Now the variation started to come which were not that easy to handle with "like". Like one case occurred to search the query in starting of the words. Like for same above input query the result set should contain
Microcompany Something
Something Somethin Microcompany
Something Microcompany
So i switched to using Regular Expressions
Now my Query turned into
select * from company where CompanyName regexp '[[:<:]]Micro';
Question: Now I want the result sorted on the closest matching index. I mean the one on which match occurred on index closer to 0 will come first and then the others. For the above search result it should be order as follow.
Microcompany Something
Something Microcompany
Something Somethin Microcompany
Is it achievable through MySQL. If yes than how? and what are the alternatives?
ORDER BY LOCATE('Micro', CompanyName)? Though I'd suggest that you also look into fulltext search, or else an engine like Apache Solr or Sphinx, since your current pattern matching searches aren't sargable.