Mysql匹配加权标签

时间:2016-08-23 20:47:59

标签: mysql sorting matching

我有3张桌子:

  • 文章(id,title,...)
  • article_tag(article_id,tag_id)
  • 标签(id,sort,...)

我通过对匹配标签的数量进行排序,找到了一篇相关文章(对于示例中ID为400的文章):

SELECT at1.article_id, COUNT( at1.tag_id ) AS tag_count
FROM article_tag AS at1
INNER JOIN article_tag AS at2 ON at1.tag_id = at2.tag_id
WHERE at2.article_id = 400
GROUP BY at1.article_id
HAVING at1.article_id != 400
ORDER BY COUNT( at1.tag_id ) DESC 
LIMIT 0 , 20

这很好用。现在我不想为不同类型的标签增加重量。在表标记中,有一个名为sort的字段。这是int,指定标记的类型。我不是所有人都有不同的意义。我可以将这些乘数放在不同的表中,或者将它们直接放在SQL代码中(只有6种)。我实际上更喜欢最后一种方法,因为那时我可以更容易地调整乘数。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您可以使用CASE表达式

SELECT at1.article_id,
       SUM(CASE at1.sort
            WHEN 1 THEN 5
            WHEN 2 THEN 3
            ...
            WHEN 6 THEN 15
           END) AS tag_weight
...
ORDER BY tag_weight DESC
LIMIT 0, 20

或者您可以使用生成相关权重的子查询加入。

SELECT at1.aticle_id, SUM(weights.weight) AS tag_weight
FROM article_tag AS at1
INNER JOIN article_tag AS at2 ON at1.tag_id = at2.tag_id
INNER JOIN (
    SELECT 1 AS sort, 3 AS weight
    UNION
    SELECT 2, 3
    UNION
    ...
    SELECT 6, 15
) as weights ON at1.sort = weights.sort
WHERE at2.article_id = 400
GROUP BY at1.article_id
HAVING at1.article_id != 400
ORDER BY tag_weight DESC 
LIMIT 0 , 20