【问题标题】:MySQL specific sorting of the result based on multiply 'LIKE' and better matching of the founded resultsMySQL 基于乘法“LIKE”对结果进行特定排序并更好地匹配已建立的结果
【发布时间】: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 子句添加顺序)?

  1. 首先是“%john%smith%junior”按 ASC 排序的所有结果
  2. 第二个所有结果,其中 userName 喜欢 '%john%smith%' 排序 ASC
  3. 最后是 userName like '%junior%' 排序 ASC 的所有结果

【问题讨论】:

    标签: mysql sorting sql-order-by


    【解决方案1】:
    ...
    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%'like '%smith%',即该模式的实际权重为@weight2 + @weight5 + @weight6

    【讨论】:

    • 太棒了!非常感谢@Akina,这正是我想要的!干杯!
    猜你喜欢
    • 2012-05-22
    • 2014-10-02
    • 1970-01-01
    • 2011-02-02
    • 2012-03-24
    • 1970-01-01
    • 2011-08-20
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多