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

时间:2013-09-02 12:26:23

标签: sql relevance

对于每一行,我希望获得每个描述的相关性与未定义数量的关键字进行比较。我知道“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

因此,如果描述包含“keyword1”和“keyword2”,则此行的relevant_description应为2。

1 个答案:

答案 0 :(得分:3)

您可以使用单独的子句执行此操作,并将它们一起添加:

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;