1

如何创建一个使用LIKE运算符匹配多个字符串的 SQL 查询,然后ORDERS根据它获得的匹配数得出结果?

另外,有没有办法存储匹配的数量,以便我以后可以在 PHP 中使用该数字进行其他计算?

我目前正在使用另一个 Stack Overflow 答案中的代码

SELECT searchtopics_topicid, searchtopics_content FROM searchtopics 
    WHERE searchtopics_content
         LIKE '%string1%' OR searchtopics_content 
         LIKE '%string2%' OR searchtopics_content
         LIKE '%string3%' 
    ORDER BY 
         case when searchtopics_content LIKE '%string1%' then 1 else 0 end + 
         case when searchtopics_content LIKE '%string2%' then 1 else 0 end + 
         case when searchtopics_content LIKE '%string3%' then 1 else 0 end 
    DESC
4

1 回答 1

2

上面的代码看起来应该可以正常工作,以存储您只需将ORDER BY案例逻辑添加到选择列表中的数字。

SELECT searchtopics_topicid
     , searchtopics_content 
     , case when searchtopics_content LIKE '%string1%' then 1 else 0 end + 
       case when searchtopics_content LIKE '%string2%' then 1 else 0 end + 
       case when searchtopics_content LIKE '%string3%' then 1 else 0 end AS hit_ct 
FROM searchtopics 
WHERE searchtopics_content LIKE '%string1%' 
   OR searchtopics_content LIKE '%string2%' 
   OR searchtopics_content LIKE '%string3%' 
ORDER BY 
     case when searchtopics_content LIKE '%string1%' then 1 else 0 end + 
     case when searchtopics_content LIKE '%string2%' then 1 else 0 end + 
     case when searchtopics_content LIKE '%string3%' then 1 else 0 end 
DESC

在 MySQL 中,您可以稍微简化一下:

    SELECT searchtopics_topicid
         , searchtopics_content 
         , searchtopics_content LIKE '%string1%' 
           + searchtopics_content LIKE '%string2%' 
           + searchtopics_content LIKE '%string3%' AS hit_ct 
    FROM searchtopics 
    WHERE searchtopics_content LIKE '%string1%' 
        + searchtopics_content LIKE '%string2%' 
        + searchtopics_content LIKE '%string3%' > 0
    ORDER BY searchtopics_content LIKE '%string1%' 
           + searchtopics_content LIKE '%string2%' 
           + searchtopics_content LIKE '%string3%' DESC
于 2013-11-11T20:16:41.363 回答