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

前端 未结 1 1606
忘掉有多难
忘掉有多难 2021-01-22 14:18

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 th

1条回答
  •  太阳男子
    2021-01-22 14:51

    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;
    

    0 讨论(0)
提交回复
热议问题