mysql – COUNT(table_name.column_name)没有给出准确的计数.我在错误的列上应用GROUP BY吗?

我有一个有点复杂的数据库结构运行跟踪产品.以下是
MySQL Workbench生成的图表:

在这种结构下,我有3个产品,我已添加.所有这三种产品都具有属性颜色和红色选项.
我在这里设置了一个sql小提琴:http://sqlfiddle.com/#!2/68470/4显示一个查询我正在运行试图让opt_count列在属性列为彩色且选项列为红色的行上说3.

几乎所有其他opt_count值也是错误的,所以我怀疑我要么没有按正确的列分组,要么我正在接近整个问题.

如何为每行显示正确的opt_count?

最佳答案 正如其他人所说,您的架构是问题,因为您有多对多的关系(许多产品可能有很多选项),这使得查询更加困难.

这是一个查询,为您提供所要求的确切输出.它显示了每个选项,分配了多少选项的唯一产品(COUNT(distinct product_id)),并提供了分配的product_id值的逗号分隔列表.

SELECT pvo.option, 
       count(distinct product_id), 
       group_concat(distinct product_id) products
  FROM (`products`)
  JOIN `product_variant_combinations` pvc using(`product_id`)
  JOIN `product_variants` pv using(`combination_id`)
  JOIN `product_variant_ao_relation` pv_ao using(`ao_id`)
  JOIN `product_variant_options` pvo using(`option_id`)
  JOIN `product_variant_attributes` pva using(`attribute_id`)
 group by pvo.option;

这是红色的输出:

红色3 111026,111025,111024

看这里:
http://sqlfiddle.com/#!2/68470/133

您询问了如何添加属性:

SELECT pva.attribute, pvo.option, count(distinct product_id), group_concat(product_id)
FROM (`products`)
JOIN `product_variant_combinations` pvc using(`product_id`)
JOIN `product_variants` pv using(`combination_id`)
JOIN `product_variant_ao_relation` pv_ao using(`ao_id`)
JOIN `product_variant_options` pvo using(`option_id`)
JOIN `product_variant_attributes` pva using(`attribute_id`)
group by pva.attribute, option

您必须在SELECT子句中的每个非聚合表达式GROUP BY.在这种情况下,两个聚合表达式是COUNT和GROUP_CONCAT,因此,您必须GROUP BY pva.attribute,pvo.option

您可能想在GROUP BY上找到一个很好的SQL教程.

点赞