简体   繁体   English

mysql获取产品的通用类别

[英]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 类别表:id,id_parent,名称
  • associations table: id_category, id_product 关联表: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. 这将返回与products表中存储的所有产品相关的所有类别ID。

Demo here 在这里演示

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

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