Mysql 按相关性和标题排序

Mysql order by relevance and title

我有一个 sql 查询搜索功能有点复杂,但效果很好。

SELECT
    SQL_CALC_FOUND_ROWS p.id as id,
    p.title as title,
    co.title as company,
    p.price as price,
    p.image_url as image_url FROM products p 
JOIN product_categories pc ON p.id = pc.product_id
JOIN categories cat ON pc.category_id = cat.id
JOIN companies co ON p.company_id = co.id

        WHERE MATCH(p.title) AGAINST("nalle" IN BOOLEAN MODE)
        OR MATCH(p.description) AGAINST("nalle" IN BOOLEAN MODE)
        OR MATCH(cat.title) AGAINST("nalle" IN BOOLEAN MODE)
        OR MATCH(co.title) AGAINST("nalle" IN BOOLEAN MODE)

    GROUP BY p.id
    ORDER BY p.title
    LIMIT :offset, :limit

现在它按产品标题排序,但应该将最相关的结果放在第一位。这意味着如果它同时匹配 p.title 和 p.description,则它比仅匹配 p.title 更相关。最好的匹配是匹配所有四个。

由于查询比较复杂,不知道如何计算。

4 个 MATCH() 函数中的每一个 returns 一个计算为 1 或 0 的布尔值,因此您可以获得所有返回值的总和并按降序排序:

ORDER BY MATCH(p.title) AGAINST("nalle" IN BOOLEAN MODE) + 
         MATCH(p.description) AGAINST("nalle" IN BOOLEAN MODE) +
         MATCH(cat.title) AGAINST("nalle" IN BOOLEAN MODE) +
         MATCH(co.title) AGAINST("nalle" IN BOOLEAN MODE) DESC

如何使用相关性得分。我找到了一个例子:

SELECT table. * ,
MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
) AS Score
FROM table
WHERE MATCH (
col1, col2, col3
) 
AGAINST (
'+(Term1) +(Term1)'
)

剩下的我相信你能想通