0

考虑以下查询:

$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

在“order 1”的情况下,两个聚合是不同的并且表现如预期。但是对于“订单 2”,这两个数字是相同的——这两个数字都是我所期望的refund_total。quant_refunded 中带有“0”的行似乎已从 order_total 聚合中排除。

希望这被解释得足够透彻。如果您需要更多信息,请告诉我,我会修改。谢谢!

4

1 回答 1

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则将保留它。

于 2013-05-16T21:17:28.653 回答