ntstha
ntstha

Reputation: 1173

Include space in mysql like search

I am having problem in using mysql like keyword in certain condition. My requirement goes like this. First, when i search for 'ABC', the result should find ABC and ABCdef but not xyzABCdef or xyzABC. It seems simple at first to use ABC%. but in condition when i search for 'heart%', it doesnot return row that have 'liver heart' because it returns only row that have heart at the beginning of the string.Then i tried using % heart%.This returned row having 'liver heart' but not those rows that have heart at the beginning of string. I am kind of stuck here..so guys help me.

EDIT With your help guys i came with the following solution but still its giving me some problem.

    SELECT q.question_id, q.question, q.date,p.fname,p.lname,p.phys_id,
p.pic_path  
            FROM questions q JOIN physiciansprofile p ON p.phys_id=q.phys_id   
         WHERE  q.question  LIKE 'heart%' OR question LIKE '% heart%' 
            AND q.question LIKE 'liver%' OR q.question LIKE '% liver%' 
    ORDER BY q.date DESC LIMIT 0,10;

But this query return heart failure and symptoms liver as well.Is there any solution for this. I need to get result containing both heart and liver and also must satisfy condition as stated before. Is there any to solve this

Upvotes: 4

Views: 14314

Answers (3)

Thorsten Kettner
Thorsten Kettner

Reputation: 95101

I just saw this old unsolved request. As someone may have the same question, I'll post the answer in spite of the request's age.

WHERE q.question LIKE 'heart%' OR question LIKE '% heart%' 
AND q.question LIKE 'liver%' OR q.question LIKE '% liver%' 

translates to

WHERE q.question LIKE 'heart%' 
OR (question LIKE '% heart%' AND q.question LIKE 'liver%')
OR q.question LIKE '% liver%' 

because AND has precedence over OR.

So one must use parentheses here. This is often the case when mixing AND and OR and it's good habit to always do so:

WHERE (q.question LIKE 'heart%' OR question LIKE '% heart%')
AND (q.question LIKE 'liver%' OR q.question LIKE '% liver%')

Upvotes: 3

Þaw
Þaw

Reputation: 2057

what about

WHERE foo LIKE '% heart%' OR foo LIKE 'heart%'

Upvotes: 1

mcalex
mcalex

Reputation: 6798

'% heart%' doesn't work because you are asking for anything, plus space, plus heart, plus anything.

Try something like:

like 'heart%' OR like '% heart%'

Upvotes: 6

Related Questions