简体   繁体   English

查询以获取相关产品,按匹配标签排序

[英]Query to get Related products sort by matching tags

im trying to make a related algorithm for products in a custom php site, with mysql. 我正在尝试使用mysql为自定义php网站中的产品制作相关算法。

I have a table for products, another for tags, and a relational one for products_tags. 我有一个用于产品的表,另一个用于标签的表,以及一个用于products_tags的关系表。

Given a product, i must find products order by number of matchings tags, with the product given. 对于给定的产品,我必须通过匹配标签的数量找到给定产品的产品订单。

Example: 例:

Product 1 tags: tag1, tag2, tag3, tag4.
Product 2 tags: tag2.
Product 3 tags: tag1, tag2, tag4.
Product 4 tags: tag1, tag5, tag2.

Result: 结果:

Product 1 related: 与产品1相关:

Product3 (3 matches) 产品3(3个匹配项)

Product4 (2 matches) 产品4(2个匹配项)

Product2 (1 match) 产品2(1个匹配项)

The idea is to do this just with one mysql query 想法是仅使用一个mysql查询来执行此操作

SELECT COUNT(1) AS count1, pt1.product_id FROM product_tags pt1 WHERE tag_id in (select tag_id from product_tags WHERE product_id = ?) AND product_id != ? 选择COUNT(1)AS count1,pt1.product_id从product_tags pt1,在哪里tag_id(从product_tags中选择tag_id,在何处product_id =?) 和product_id!=? GROUP BY pt1.product_id ORDER BY count1 DESC GROUP BY pt1.product_id ORDER BY count1 DESC

SELECT COUNT(1) AS count1, pt1.product_id FROM product_tags pt1 WHERE tag_id in (select tag_id from product_tags WHERE product_id = ?) AND product_id != ? GROUP BY pt1.product_id ORDER BY count1 DESC

更改为排除原始产品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM