Mysql: Order by like?

倾然丶 夕夏残阳落幕 提交于 2019-11-27 00:27:57
order by case 
    when name LIKE "%John%" then 1 
    when name LIKE "%Doe%"  then 2 
    else 3 
end

Read up on Boolean Fulltext Searches, with which you can do ordering.

To build on RedFilter's answer, you could make the rows that have both keywords to be at the top:

order by case 
when (name LIKE "%John%" and name LIKE "%Doe%") then 1 
when name LIKE "%John%" then 2
when name LIKE "%Doe%"  then 3
end
 SELECT * 
 from
 (
  SELECT u.*, 1 OrderNum 
  FROM users 
  WHERE (name LIKE "%John%")
  UNION 
  SELECT u.*, 2 OrderNum 
  FROM users 
  WHERE (name LIKE "%Doe%")
  )
  Order by OrderNum

My example will Order all of the John's Alphabetically followed by the Doe's.

ORDER BY CASE
    WHEN name LIKE "John%Doe" THEN CONCAT('a',name)
    WHEN name LIKE "John%"    THEN CONCAT('b',name)
    WHEN name LIKE "%Doe"     THEN CONCAT('c',name)
    ELSE name  
END  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!