Order sql result by occurrence of a set of keywords in a string

半腔热情 提交于 2019-12-20 03:15:15

问题


For each rows, I want to get the relevance of each description compared to an undefined number of keywords. I know that "THEN +1" does not work, but I would like to come to this result (...to have a number (starting from 0 each rows) that is incremented for each keyword present)

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

So, if a description contains "keyword1" and "keyword2", relevance_description should be 2 for this row.


回答1:


You can do this with separate clauses, and add them together:

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;

In some databases, booleans are treated as integers, so you could just write:

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


来源:https://stackoverflow.com/questions/18573270/order-sql-result-by-occurrence-of-a-set-of-keywords-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!