我在开一家电子商店,所以我有三张桌子:
1)goods

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

2)tags
id      | title
--------+-----------
1       | Toy
2       | Boys
3       | Girls

3)links
goods_id| tag_id
--------+-----------
1       | 1
1       | 2
2       | 1
2       | 2
2       | 3
3       | 3

所以我需要用这样的算法打印相关商品:用标签得到与所选商品最相似的商品。大多数标签是相互的-最适合的项目是
所以goods#1的结果应该是:goods#2goods#3
对于goods#2goods#1goods#3
对于goods#3goods#2goods#1
我不知道如何用一个查询就可以通过相互标记的计数来排序相似的商品

最佳答案

此查询将返回具有最大标签数量的所有项:

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
  )

请参见fiddlehere
或者这个将返回所有项目,甚至那些没有共同标记的项目,按共同描述中的标记数排序:
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;

关于mysql - sql查询通过标签确定最相似的商品,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17370847/

10-10 08:54