How to prioritize a LIKE query select based on string position in field?

梦想的初衷 提交于 2019-12-01 05:13:49

If you mean to prioritize matches that are Exactly at the start...

SELECT id, country
FROM tblPlaces
WHERE country LIKE '%ca%'
ORDER BY CASE WHEN country LIKE 'ca%' THEN 0 ELSE 1 END, country
LIMIT 2

EDIT

More generic and possibly faster (Assuming "closer to the start the 'better' the match")...

SELECT id, country
FROM tblPlaces
WHERE country LIKE '%ca%'
ORDER BY INSTR(country, 'ca'), country
LIMIT 2
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!