[英]PHP/MySQL search results - exact match first
Let's say I have a series of options which the user is searching for via a JQuery autocomplete dropdown:假设我有一系列用户正在通过 JQuery 自动完成下拉菜单搜索的选项:
Shiplake
希普莱克
Lake
湖
Uplake
上湖
Downlake
下湖
When the user types in "Lake" they get the results sorted alphabetically:当用户输入“Lake”时,他们会得到按字母顺序排序的结果:
Downlake
下湖
Lake
湖
Shiplake
希普莱克
Uplake
上湖
The code in question is something like有问题的代码类似于
"SELECT name FROM names WHERE name LIKE '%".$q."%' ORDER BY name ASC"
But what I'd like is if the query matches EXACTLY a name, it would appear first then everything else alphabetically - so但我想要的是,如果查询完全匹配一个名称,它会首先出现,然后按字母顺序出现其他所有内容 - 所以
Lake
湖
Downlake
下湖
Shiplake
希普莱克
Uplake
上湖
How can this be achieved?如何做到这一点?
You can always add an ORDER BY
clause:您始终可以添加
ORDER BY
子句:
ORDER BY name=? DESC, name
Where that sorts by exact match first, then by the actual value second.首先按完全匹配排序,然后按实际值排序。
?
represents a placeholder value for the search term.表示搜索词的占位符值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.