简体   繁体   中英

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.

I have a table for products, another for tags, and a relational one for 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:

Product3 (3 matches)

Product4 (2 matches)

Product2 (1 match)

The idea is to do this just with one mysql query

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

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

更改为排除原始产品

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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