我有一张表,我根据名称、描述、category_name来搜索记录,我希望记录的顺序是什么。
匹配名称或部分名称的结果。
然后是与描述以及category_name相匹配的结果。
与唯一的category_name匹配的结果。
与描述相符的结果
请看,我是想根据记录的匹配度来排序。简单的按名称排序,并根据名称对所有记录进行排序。
示例数据。
名称,描述,类别_名称
abc,xyz_usama,asz。
usama,这是描述,人
亚伯拉罕、xyz、乌萨马
Jhon,这是usama,usama这个人
现在如果我用关键词usama搜索:结果应该是:
2 (与名字匹配)
4(说明+类别)
3(类别)
1(说明)
你可以使用 case
表达式`。 你的问题并不是很清楚数据是什么样子的,但想法是。
order by (case when name like '%' || :search || '%'
then 1
when category_name like '%' || :search || '%' and
description like '%' || :search || '%'
then 2
when category_name like '%' || :search || '%'
then 3
when description like '%' || :search || '%'
then 4
else 5
end)
ORDER BY
/* Results that matched with name or part of the name, */
name LIKE 'name_pattern' DESC,
/* Then Results that matched with the description as well as category_name, */
/* Results that matched with the only category_name, */
category_name LIKE `category_name_pattern` DESC,
description LIKE `description_pattern` DESC
/* Results that matched with the description */
/* i.e. all another records */
如果所有的模式都是相同的子串 你可以用简单的...
ORDER BY LOCATE('pattern', CONCAT(name, category_name, description))