sql query to determine the most similar goods by tags

前端 未结 3 2198
余生分开走
余生分开走 2021-02-11 07:48

i\'m making an e-store, so i have 3 tables:

1) goods

id      | title
--------+----------- 
1       | Toy car
2       | Toy pony
3       | Do         


        
3条回答
  •  旧巷少年郎
    2021-02-11 08:37

    This query will return all items that have the maximum number of tags in common:

    SET @item = 1;
    
    SELECT
      goods_id
    FROM
      links
    WHERE
      tag_id IN (SELECT tag_id FROM links WHERE goods_id=@item)
      AND goods_id!=@item
    GROUP BY
      goods_id
    HAVING
      COUNT(*) = (
        SELECT
          COUNT(*)
        FROM
          links
        WHERE
          tag_id IN (SELECT tag_id FROM links WHERE goods_id=@item)
          AND goods_id!=@item
        GROUP BY
          goods_id
        ORDER BY
          COUNT(*) DESC
        LIMIT 1
      )
    

    Please see fiddle here.

    Or this one will return all items, even those with no tags in common, ordered by the number of tags in common desc:

    SELECT
      goods_id
    FROM
      links
    WHERE
      goods_id!=@item
    GROUP BY
      goods_id
    ORDER BY
      COUNT(CASE WHEN tag_id IN (SELECT tag_id FROM links WHERE goods_id=@item) THEN 1 END) DESC;
    

提交回复
热议问题