Question

I wrote a query where a user can input a string and get the data related to that string back from the database.

For example, a user will input Apple even though the full name is Apple Inc.

The code would be laid out as so...

and Description like '%Apple%'

The problem with this is, it will return Snapple along with Apple.
Aside from removing the first "%" wildcard and making the user type more, how can I limit the results to just Apple?

Was it helpful?

Solution

Use a regular expression:

WHERE Description RLIKE '[[:<:]]apple[[:>:]]'

[[:<:]] matches the beginning of a word, [[:>:]] matches the end of a word.

See the documentation for all the regexp operators supported by MySQL

OTHER TIPS

Firstly - string comparison with wild cards (especially leading wild cards) doesn't really scale using "like". You might want to look at full-text searching instead. This basically gives you "google-like" text searching capabilities.

To answer your question, in most cases, "Apple" is a better match than "Snapple" for the term "apple". So, you could include the concept of "match quality" in the search - something like:

select *, 10 as MatchQuality
from table
where description like 'Apple'
union
select *, 5 as MatchQuality
from table
where description like 'Apple%'
union 
select *, 1 as MatchQuality
from table
where description like '%Apple%'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top