【发布时间】:2022-01-12 03:37:42
【问题描述】:
我正在尝试构建搜索引擎,想知道有没有办法根据更精确的匹配对结果进行排序?
我有一个简单的表 library,其中存储了用户名:
| userName |
|---|
| john hampton |
| smith horne |
| john smith junior |
| kevin spencer |
| john white smith |
| luke junior |
| alan smith junior |
基于搜索字段输入。例如,如果我想搜索 john smith junior,我不仅要检查全名匹配,还要检查名称的匹配部分。所以预期的结果应该是:
| userName |
|---|
| john smith junior |
| john white smith |
| alan smith junior |
| john hampton |
| smith horne |
| luke junior |
第一行需要评分最高,因为我们有三个匹配项,第二行和第三行有两个匹配项,其余只有一个匹配项,但按输入字段提交排序。
我开始构建以下查询:
SELECT `userName`
FROM `library`
WHERE `userName` like '%john%smith%junior'
OR `userName` like '%john%smith%'
OR `userName` like '%john%junior%'
OR `userName` like '%smith%junior%'
OR `userName` like '%john%'
OR `userName` like '%smith%'
OR `userName` like '%junior%'
ORDER BY ???
但是我阻止了如何对结果进行排序,所以我的问题是 - 是否可以在 ORDER BY 中添加一些特殊子句以根据需要对结果进行排序(优先级基于 where 子句添加顺序)?
- 首先是“%john%smith%junior”按 ASC 排序的所有结果
- 第二个所有结果,其中
userName喜欢 '%john%smith%' 排序 ASC - 等
- 最后是
userNamelike '%junior%' 排序 ASC 的所有结果
【问题讨论】:
标签: mysql sorting sql-order-by