Select products by multiple attributes, using AND instead OR concatenator, Data model EAV

后端 未结 1 1722
天涯浪人
天涯浪人 2021-01-14 07:52

I have an issue with a query for eCommerce website products filter.

I have EAV data model like this:

products          [id, title....]
attributes             


        
相关标签:
1条回答
  • 2021-01-14 08:47

    Your subquery should be like this:

    SELECT
      attributes_entity.product_id
    FROM
      attributes_entity INNER JOIN attributes
      ON attributes_entity.attribute_id=attributes.id
      INNER JOIN attributes_values ON
      attributes_entity.value_id=attributes_values.id 
    WHERE 
      (attributes.name="Memory" AND attributes_values.value="16GB") 
      OR
      (attributes.name="Color" AND attributes_values.value="Gold")
    GROUP BY
      attributes_entity.product_id
    HAVING
      COUNT(DISTINCT attributes.name)=2
    

    this solution uses a GROUP BY subquery. You have to use OR because the attribute can't be Memory and Color at the same time on the same row, they can both be true but on different rows. COUNT(DISTINCT attributes.name) counts the number attributes that either Color or Memory, if it's 2 then there is at least 1 row where the first condition is true and 1 row where the other is also true.

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