简体   繁体   中英

Mysql get the common categories of products

I am trying to create a filtering sistem for products.

I have:

  • products table
  • categories table: id, id_parent, name
  • associations table: id_category, id_product

I want to search the table of products and from the results to create the common categories that they have so they can be filtered even more.

How do I get only the categories that are found in all the products list?

Thanks for any help!

You can use the following query:

SELECT id_category
FROM (SELECT id_category, COUNT(DISTINCT id_product) AS cnt
      FROM associations
      GROUP BY id_category ) AS t
WHERE t.cnt = (SELECT COUNT(DISTINCT id) FROM products)

This will return all category ids that are related to all products stored in the products table.

Demo here

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