我正在嘗試構建搜索引擎,想知道有沒有辦法根據更精確的匹配對結果進行排序?
我有一個簡單的表library,其中存盤了用戶名:
| 用戶名 |
|---|
| 約翰漢普頓 |
| 史密斯霍恩 |
| 小約翰史密斯 |
| 凱文斯賓塞 |
| 約翰懷特史密斯 |
| 小盧克 |
| 小艾倫·史密斯 |
基于搜索欄位輸入。例如,如果我要搜索,john smith 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 - 等等。
- 最后是
userName像 '%junior%' 排序 ASC的所有結果
uj5u.com熱心網友回復:
...
ORDER BY (`userName` like '%john%smith%junior') * @weight1
(`userName` like '%john%smith%') * @weight2
(`userName` like '%john%junior%') * @weight3
(`userName` like '%smith%junior%') * @weight4
(`userName` like '%john%') * @weight5
(`userName` like '%smith%') * @weight6
(`userName` like '%junior%') * @weight7
考慮到條件的實際權重是它及其所有子條件的權重之和。
例如,匹配條件的行like '%john%smith%'也匹配like '%john%'and like '%smith%',即該模式的實際權重為@weight2 @weight5 @weight6。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/411328.html
標籤:
上一篇:使用本機方法對陣列進行排序的問題
