简体   繁体   中英

SQL Searching and Order case of where clause

I have simple a search function

SELECT bar FROM `foo` 
WHERE (bar like '%search1%') || (bar like '%search2%') ... (maybe more)

I want to order result by which one is most acurate answer.

If my table like this

1 : sometext search1 sometext
2 : sometext search2 sometext
3 : search1 search2 sometext

i want to bring 3rd row to top of results (cause its contain both of search1 and search2)

You can do this in the order by . Here is a general method:

SELECT bar
FROM `foo` 
ORDER BY ((case when bar like '%search1%' then 1 else 0 end) +
          (case when bar like '%search2%' then 1 else 0 end) +
          . . .
         ) desc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM