Ordering items with matching tags by number of tags that match

前端 未结 2 1503
[愿得一人]
[愿得一人] 2021-02-04 13:10

I\'m trying to figure out how to order items with matching tags by the number of tags that match.

Let\'s say you have three MySQL tables:

  • tags(tag_id
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 13:30

    Try something like this:

    select article_id, count(tag_id) as common_tag_count
    from articles_tags 
    group by tag_id
    where tag_id in (
        select tag_id from articles_tags where article_id = 2
    ) and article_id != 2
    order by common_tag_count desc;
    

    Syntax may need a little tweaking for MySQL.

    or this one that actually works: ;-)

    SELECT at1.article_id, Count(at1.tag_id) AS common_tag_count
    FROM articles_tags AS at1 INNER JOIN articles_tags AS at2 ON at1.tag_id = at2.tag_id
    WHERE at2.article_id = 2
    GROUP BY at1.article_id
    HAVING at1.article_id != 2
    ORDER BY Count(at1.tag_id) DESC;
    

提交回复
热议问题