0
$query = "
SELECT a_orders.id, a_orders.billing, a_orders.type, 
    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,
    GROUP_CONCAT(DISTINCT a_order_rows.date_refunded) as refund_dates
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_order_rows.date_refunded DESC, a_orders.id DESC
LIMIT 50";

$query = "
SELECT a_orders.id, a_orders.billing, a_orders.type, 
    SUM(a_order_rows.quant_refunded*a_order_rows.price*((100-a_orders.discount)*.01))+a_orders.refund_adjustment as refund_total, 
    SUM(a_order_rows.quant*a_order_rows.price*((100-a_orders.discount)*.01)) as order_total,
    GROUP_CONCAT(DISTINCT a_order_rows.date_refunded) as refund_dates
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_order_rows.date_refunded DESC, a_orders.id DESC
LIMIT 50";

注意+a_orders.refund_adjustment查询 2 的第 2 行?只是添加它正在改变结果的顺序。a_orders.refund_adjustment,如果选择该列而不将其添加到聚合中(例如在第 1 行之后添加) ,也会发生同样的事情a_orders.type,

将该列添加到组合中后,结果不再按预期排序date_refunded DESC。是什么赋予了?我无法理解这会如何以任何方式影响结果顺序。

4

1 回答 1

0

你是a_order_rows.date_refunded在做一个之后订购的group by。聚合不包括该字段。

MySQL 接受任何其他数据库中的错误。但是,它会从其中一个匹配行中选择一个任意值来放置在该字段中。这个任意值可以从一次查询执行更改为下一次执行。你不能依赖它。

如果您想以date_refunded更稳定的方式排序,请使用聚合函数:

ORDER BY min(a_order_rows.date_refunded) DESC, a_orders.id DESC

或者

ORDER BY max(a_order_rows.date_refunded) DESC, a_orders.id DESC
于 2013-05-16T22:58:54.380 回答