首页 > 解决方案 > sql 按最匹配记录排序

问题描述

我编写了 sql 查询来匹配关键字中的任何单词。现在我想订购最匹配的单词。我怎样才能做到这一点。

这是我的 sql 查询。

select a.itemId, a.tags from items a
where a.quantity <> 0 and a.deleted <> 1 and a.tags rlike replace("master guide grade 10", ' ', '|')

例如,如果有记录“主指南等级 10”,那么它首先出现,然后如果有记录“主指南等级 6” ,那么我想获得结果集。我怎样才能做到这一点。

提前致谢!

标签: mysqlsql

解决方案


您可以分别查找每个值并将匹配项相加:

select a.itemId, a.tags
from items a
where a.quantity <> 0 and
      a.deleted <> 1 and
      a.tags rlike replace('master guide grade 10', ' ', '|')
order by (a.tags like '%master%') + (a.tags like '%guide%') + (a.tags like '%grade%') + (a.tags like '%10%') desc

推荐阅读