考虑以下问题:
$query = "
SELECT a_orders.id, a_orders.billing,
SUM(a_order_rows.quant_refunded*a_order_rows.price*((100-a_orders.discount)*.01)) as refund_total,
SUM(a_order_rows.quant*a_order_rows.price*((100-a_orders.discount)*.01)) as order_total
FROM a_order_rows JOIN a_orders
ON a_order_rows.order_id = a_orders.id
WHERE a_order_rows.quant_refunded > 0
GROUP BY a_orders.id, a_orders.billing
ORDER BY a_orders.id DESC
LIMIT 50";
SUM()的两种用法是尝试汇总订单总额和已退款的总金额。当quant_refunded字段不为0时,它们正确地出现...例如,为了简单起见,除了主键,item_id,假设每一行都是唯一的项目):
Table: a_order_rows
Fields: order_id, quant, quant_refunded
1, 1, 1
1, 2, 1
2, 1, 1
2, 1, 0
在“订单1”的情况下,两个聚合是不同的并且表现如预期。但对于“订单2”,这两个数字是相同的 - 这两个数字都是我期望的退款数量。似乎quant_refunded中带有“0”的行正在从order_total聚合中排除。
希望这个解释得足够彻底。如果您需要更多信息,请告诉我,我会修改。谢谢!
答案 0 :(得分:1)
$query = "
SELECT a_orders.id, a_orders.billing,
SUM(a_order_rows.quant_refunded*a_order_rows.price*((100-a_orders.discount)*.01)) as refund_total,
SUM(a_order_rows.quant*a_order_rows.price*((100-a_orders.discount)*.01)) as order_total
FROM a_order_rows JOIN a_orders
ON a_order_rows.order_id = a_orders.id
GROUP BY a_orders.id, a_orders.billing
HAVING MAX(a_order_rows.quant_refunded) > 0
ORDER BY a_orders.id DESC
LIMIT 50";
将其更改为HAVING子句。如果任何quant_refunded行是> 0,HAVING MAX
将保留它。