mysql SORT BY唯一字匹配的数量

时间:2013-10-23 11:14:55

标签: mysql sql-order-by

我发现了很多问题,要求提供大量的外表,但没有一个问题与我希望做的一样。

动态生成的(预准备语句)查询将产生如下内容:

SELECT * FROM products WHERE 
( title LIKE ? AND title LIKE ? ) AND 
( content LIKE ? OR content LIKE ? ) AND 
( subtitle LIKE ? AND author LIKE ? )
ORDER BY relevance LIMIT ?,?

输入的字词数量(以及LIKE的数量)是标题,内容和作者的可变数量(取决于搜索查询)。

现在我添加了ORDER BY relevance。但我希望这个顺序是匹配的内容字段中的唯一单词数量。 (注意:不是关于外观的数量,而是关于content列中输入的字符串至少一个匹配的数量。)

示例表products

id | title   | subtitle  | content
------------------------------------
1  | animals | cat       | swim swim swim swim swim swim swim
2  | canimal | fish      | some content
3  | food    | roasted   | some content
4  | animal  | cat       | swim better better swims better something else
5  | animal  | cat       | dogs swim better

示例查询(填写预备语句?):

SELECT * FROM products WHERE 
( title LIKE %animal% ) AND 
( content LIKE %dog% OR content LIKE %swim% OR content LIKE %better% ) AND 
( subtitle LIKE %cat% )
ORDER BY relevance LIMIT 0,10

预期结果(按正确顺序排列!):

id      | amount of matches
-----------------
5       | 3 (dog, swim, better)
4       | 2 (swim, better)
1       | 1 (swim)

我有一个Innodb表和mysql版本低于5.6,因此我无法使用MATCH...AGAINST。 我以为这可以通过WHEN CASE ... THEN来解决。但我不知道如何创建这种排序。

2 个答案:

答案 0 :(得分:1)

您可以通过多种方式执行此操作,例如

ORDER BY SIGN(LOCATE('dog',content))+
         SIGN(LOCATE('swim',content))+
         SIGN(LOCATE('better',content)) DESC

SQLFiddle demo

或CASE

ORDER BY 
CASE WHEN content LIKE '%dog%' 
        THEN 1
        ELSE 0
END
+
CASE WHEN content LIKE '%swim%' 
        THEN 1
        ELSE 0
END
+
CASE WHEN content LIKE '%better%' 
        THEN 1
        ELSE 0
END

DESC

答案 1 :(得分:1)

像这样检查。

    SELECT id,CONCAT_WS('-',COUNT(LENGTH(content) - LENGTH(REPLACE(content, ' ', '')) + 1),REPLACE(content,' ',',')) AS amount of matches FROM products 
        WHERE 
        ( title LIKE %animal% ) AND 
        ( content LIKE %dog% OR content LIKE %swim% OR content LIKE %better% ) AND 
        ( subtitle LIKE %cat% )
        GROUP BY id
ORDER BY id