我有一个实体属性值的索引表,如下所示:
+-----------+--------------+----------+-------+| entity_id | attribute_id | store_id | value |+-----------+--------------+----------+-------+| 38 | 190 | 1 | 22 || 38 | 190 | 1 | 23 || 39 | 190 | 1 | 22 || 39 | 190 | 1 | 23 || 39 | 190 | 1 | 42 || 40 | 190 | 1 | 22 || 41 | 190 | 1 | 54 || 42 | 190 | 1 | 54 || 43 | 190 | 1 | 22 || 44 | 190 | 1 | 22 || 45 | 190 | 1 | 54 |+-----------+--------------+----------+-------+
如您所见,单个实体可以对单个属性具有多个值(entity_id38具有values 22,23),并且这些值不是每个实体唯一的(entity_id38,39两者共享value22)。
要解决的第一个问题是获取每个值的不同实体数;这很容易通过以下方法实现:

SELECT value, COUNT(entity_id) AS count
FROM catalog_product_index_eav
WHERE attribute_id=190
GROUP BY value;

结果是:
+-------+-------+| value | count |+-------+-------+| 22 | 5 || 23 | 2 || 42 | 1 || 54 | 3 |+-------+-------+
我的问题是如何在这个计数中嵌套一个或条件,即:对于某个特定值y,对于每个值x,计算具有值x或y的实体的数量。
我想在一个查询中完成此操作。例如,对于attribute_id190和value23,上述示例的输出应为:
+-------+-------+| value | count |+-------+-------+| 22 | 5 | # all entities with value 22 happen to have 23 as well| 23 | 2 | that is, one is a subset of the other| 42 | 2 | # intersection is nonempty| 54 | 5 | # sets are disjoint+-------+-------+

最佳答案

select c1.value,
( SELECT COUNT(DISTINCT entity_id) as count
  FROM catalog_product_index_eav
  where attribute_id=81
  and (value=c1.value || value=7) ) as count
FROM catalog_product_index_eav c1
WHERE attribute_id=81
GROUP BY c1.value

10-06 13:57