SQL: Get Products from a category but also must be in another set of categories

后端 未结 1 1823
野趣味
野趣味 2020-12-11 19:53

I am currently stuck in a situation. The scenario is this. I have products who may be associated with multiple categories. The data structure is shown below:



        
相关标签:
1条回答
  • 2020-12-11 20:20

    This type of problem is called relational division.

    There are two common solutions:

    1. First solution strings together the matching categories and compares to a fixed string:

      SELECT p2c.product_id
      FROM oc_product_to_category p2c
      GROUP BY p2c.product_id
      HAVING GROUP_CONCAT(p2c.category_id SEPARATOR ',' ORDER BY p2c.category_id) = '1,2'
      
    2. Second solution does a JOIN for each required value:

      SELECT p.product_id 
      FROM oc_product p 
      INNER JOIN oc_product_to_category p2c1 
        ON (p.product_id = p2c1.product_id AND p2c1.category_id = 1) 
      INNER JOIN oc_product_to_category p2c2 
        ON (p.product_id = p2c2.product_id AND p2c2.category_id = 2) 
      

    I cover these solutions in my presentation SQL Query Patterns, Optimized. I found in my tests that the join solution is much better for performance.


    @Tom's suggestion is right, here's what that would look like in a complete query:

        SELECT p.product_id, GROUP_CONCAT(p2c3.category_id SEPARATOR ',') AS categories
        FROM oc_product p 
        INNER JOIN oc_product_to_category p2c1 
          ON (p.product_id = p2c1.product_id AND p2c1.category_id = 1) 
        INNER JOIN oc_product_to_category p2c2 
          ON (p.product_id = p2c2.product_id AND p2c2.category_id = 2) 
        INNER JOIN oc_product_to_category p2c3
          ON (p.product_id = p2c3.product_id)
        GROUP BY p.product_id;
    

    The DISTINCT that @Tom suggests shouldn't be necessary, because your p2c table should have a UNIQUE constraint over (product_id, category_id).

    0 讨论(0)
提交回复
热议问题