[英]MySQL issue with descending order
My query : 我的查询:
$strSQL = "Select customers.*, count(ordersbase.OrderID) As Orders, ordersbase.OrderTime
From customers
Inner Join ordersbase On customers.ID = ordersbase.CustomerID
Group By customers.ID
Order By customers.ID, ordersbase.OrderTime Desc;";
Orders table: 订单表:
I expected to get the OrderTime
value as 20181008000000
(highest value in descending order) but it returns the other one: 我希望获得的
OrderTime
值为20181008000000
(降序排列的最高值),但它返回另一个值:
"0": {
"Orders": 2,
"OrderTime": "20181006000000"
},
Data is stored in an unordered fashion. 数据以无序方式存储。 Any non-aggregated column (which is not functionally dependent to columns in
Group By
) in the Select
clause, and also not specified explicitly inside the GROUP BY
clause, is non-deterministic. Select
子句中的任何未聚合的列(在功能上不依赖于Group By
列),并且也未在GROUP BY
子句中显式指定,这是不确定的。 You need to use Max()
function to get the latest order time. 您需要使用
Max()
函数来获取最新的订购时间。 Do Read: SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by 请阅读: SELECT列表不在GROUP BY子句中,并且包含未聚合的列....与sql_mode = only_full_group_by不兼容
Order by
is processed after grouping is already done. 分组后,将处理
Order by
。 So, your usage of Order by
does not work. 因此,您对
Order by
的使用不起作用。
Try the following instead: 请尝试以下操作:
$strSQL = "Select customers.*,
count(ordersbase.OrderID) As Orders,
MAX(ordersbase.OrderTime)
From customers
Inner Join ordersbase On customers.ID = ordersbase.CustomerID
Group By customers.ID
Order By customers.ID";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.