查询中的 MySQL 子选择

标签 mysql

我想从我的查询中得到以下结果:

id_product_attribute | id_product | reference | name         | total
12                   | 1          | 234235    | product_name | 2
14                   | 2          | 235435    | product_name | 7
16                   | 3          | 235325    | product_name | 4

等等

但是当我使用这个查询时:

select pa.id_product_attribute, p.id_product, pa.reference, cl.name, sum(od.product_quantity) as total
from ps_product_attribute pa
left join ps_order_detail od on od.product_attribute_id = pa.id_product_attribute
left join ps_product p on pa.id_product = p.id_product
left join ps_category_product cp on cp.id_product = p.id_product
left join ps_category_lang cl on cp.id_category = cl.id_category
where cp.id_category = 141 and cl.id_lang = 6;

它只给我这个结果:

id_product_attribute | id_product | reference | name         | total
12                   | 1          | 234235    | product_name | 13

所以在“总计”列中,它显示了所有的总计,而不是每行单独显示。

谁能告诉我我在查询中做错了什么?

最佳答案

您的源数据会有所帮助,但至少您最后忘记了GROUP BY。对于当前查询,您应该添加;

GROUP BY pa.id_product_attribute, p.id_product, pa.reference, cl.name

使用 MySQL,您可以选择 GROUP BY 较少的列,并在其他列中随机选择值,但如果可能,您应该 GROUP BY 所有列它们上面没有聚合(如本例中的 SUM)。

关于查询中的 MySQL 子选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17718017/

相关文章:

mysql - 如何处理具有多种不同上下文的多种语言的翻译?

php - 为mysql textarea添加换行符

mysql - 使用 liquibase.properties 的 Liquibase MySQL JDBC 驱动程序连接错误

php - 使用数据库连接时我的文件损坏

php - 为什么在以下情况下未导入数据库转储?

mysql - 根据多行的总分对 mysql 中的用户进行排名

MySql:使用 WHERE 子句将数据从一个表复制到另一个表

用于读取中间记录的 SQL

mysql - MySQL 中可接受的分组最大值技术

php - 我的图像没有下载到我的数据库表