0

In a query in which I am looking for results based on the title of articles, I use the LIKE part as followed:

WHERE title LIKE %searchquery%

In my database one title is like this:

Economy in America

My problem:

With my current query, this title does NOT get listed, when the user enters the following searchquery:

america economy

When the user enters only one of these terms, everything works fine and the title gets listed.

How come?

How do I need to adjust my query so that my sql query will also work when the user enters more than one term?

4
  • If the more terms are in the same column, you could try replacing all whitespaces with % signs eg.: WHERE title LIKE %america%economy% Commented Jun 18, 2015 at 9:28
  • What language are you using? Commented Jun 18, 2015 at 9:29
  • MySQL with PHP. Using "AND" works. the title, however does not get displayed, when the user has a typo, for example when he enters "amrica economy" or "america ecnomy"... how can I also consider typos for the title to appear? Commented Jun 18, 2015 at 9:38
  • 1
    @Max thats a completely different story, you should start learning about terms like Levenshtein distance, Soundex, generating and comparing key similarity. Commented Jun 18, 2015 at 10:07

3 Answers 3

1

The MySQL LIKE operator is limited in that it doesn't offer full regex support of the sort for which you are really looking. That being said, one option you could try would be to split your search query terms and then join multiple LIKE conditions using AND. Consider this example:

WHERE title LIKE %queryterm1% AND LIKE %queryterm2%

If queryterm1 be 'america' and queryterm2 be 'economy', then this would match the title 'Economy in America'.

Sign up to request clarification or add additional context in comments.

2 Comments

this works, thank you. the title, however does not get displayed, when the user has a typo, for example when he enters "amrica economy" or "america ecnomy"... how can I also consider typos for the title to appear?
There is no easy way to do this with MySQL AFAIK. Have a look here for an article which will get you started thinking about this challenging problem.
0

You will need to split the query by whitespaces and then add multiple LIKE statements like this:

WHERE title LIKE '%america%' AND title LIKE '%economy%'

Comments

0

As @Tim says, you must write some routine in your application to divide the string terms and inject them in the select where clause. Or you may need to write some stored procedure for that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.