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

喜夏-厌秋 提交于 2019-12-01 08:47:24

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!