Include space in mysql like search

假装没事ソ 提交于 2019-12-24 00:53:45

问题


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


回答1:


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

Try something like:

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



回答2:


what about

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



回答3:


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%')


来源:https://stackoverflow.com/questions/17228924/include-space-in-mysql-like-search

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!