选择其他列会影响ORDER BY子句吗?

时间:2013-05-16 22:22:00

标签: sql select sql-order-by

$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";

在第2行的第2行中注意+a_orders.refund_adjustment?只需添加即可改变结果的顺序。如果选择该列而不将其添加到聚合中,则会发生相同的情况(例如,在第1行的a_orders.refund_adjustment,之后添加a_orders.type,)。

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

1 个答案:

答案 0 :(得分: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