6

我发现很多问题都要求出现次数,但没有一个问题与我希望做的一样。

动态生成的(准备好的语句)查询将产生如下结果:

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)

我有一个低于 5.6 的 Innodb 表和 mysql 版本,因此我不能使用MATCH...AGAINST. 我在想这可以用WHEN CASE ... THEN. 但我不知道如何创建这种排序。

4

2 回答 2

1

例如,您可以通过多种方式做到这一点

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

SQLFiddle 演示

或与 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
于 2013-10-23T11:39:12.647 回答
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
于 2013-10-23T11:59:44.157 回答