基于匹配的SQL排序

问题描述 投票:0回答:1

我有一张表,我根据名称、描述、category_name来搜索记录,我希望记录的顺序是什么。

  1. 匹配名称或部分名称的结果。

  2. 然后是与描述以及category_name相匹配的结果。

  3. 与唯一的category_name匹配的结果。

  4. 与描述相符的结果

请看,我是想根据记录的匹配度来排序。简单的按名称排序,并根据名称对所有记录进行排序。

示例数据。

名称,描述,类别_名称

  1. abc,xyz_usama,asz。

  2. usama,这是描述,人

  3. 亚伯拉罕、xyz、乌萨马

  4. Jhon,这是usama,usama这个人

现在如果我用关键词usama搜索:结果应该是:

2 (与名字匹配)

4(说明+类别)

3(类别)

1(说明)

mysql sql laravel sql-order-by
1个回答
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)

1
投票
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))
© www.soinside.com 2019 - 2024. All rights reserved.