通过字符串中一组关键字的出现对sql结果进行排序



对于每一行,我想获得每个描述与未定义数量的关键字的相关性。我知道"THEN+1"不起作用,但我想得到这个结果(……有一个数字(每行从0开始),每个关键字都会递增)

SELECT *,
    (CASE description LIKE '%keyword1%' THEN +1 
          description LIKE '%keyword2%' THEN +1
          (...) 
          ELSE 0
    END) as relevance_description
FROM (...)
ORDER BY relevance_description DESC

因此,如果描述包含"关键字1"one_answers"关键字2",则此行的相关性description应为2。

您可以使用单独的子句来完成此操作,并将它们添加在一起:

SELECT *,
       ((CASE description LIKE '%keyword1%' THEN 1 else 0 end) +
        (case description LIKE '%keyword2%' THEN 1 else 0 end) +
        . . .
       ) as relevance_description
FROM (...)
ORDER BY relevance_description DESC;

在一些数据库中,布尔值被视为整数,因此您可以只写:

SELECT *,
       ((description LIKE '%keyword1%') +
        (description LIKE '%keyword2%') +
        . . .
       ) as relevance_description
FROM (...)
ORDER BY relevance_description DESC;

相关内容

  • 没有找到相关文章

最新更新