Mysql

Mysql 查詢 group by 與 order by desc 結合

  • August 31, 2020

我有以下查詢。

SELECT Day(vehicleTrip.startDateTime) As day, 
      Month(vehicleTrip.startDateTime) As month,
      Sum(TIMESTAMPDIFF(SECOND, startDateTime, endDateTime )) As totalDuration,
      count(vehicleTrip.startDateTime) As totalTrip, 
      sum(endMileage-startMileage) As totalMleage
FROM vehicleTrip                            
WHERE vehicleTrip.vehicleID=:vehicleID
 AND vehicleTrip.vehicleEndCodeID!=1
 AND vehicleTrip.startDateTime BETWEEN :startDateTime And :endDateTime                             
Group By Day(vehicleTrip.startDateTime),Month(vehicleTrip.startDateTime)

目前它工作正常,因為它可以按每日日期分組duration, totalTrip, totalMileage etc.但唯一的問題是我希望日期由 desc 安排。我試過按它給出的 startDateTime desc 下訂單me error that its not in GROUP By clause and containts nonaggregated column。我已經嘗試了很多方法,比如把它Max(vehicleTrip.startDateTime)還是一樣的。我怎樣才能最好地解決這個問題?

下面是我的表格設計及其索引。

CREATE TABLE `vehicleTrip` (
 `vehicleEndCodeID` tinyint NOT NULL DEFAULT '1',
 `vehicleID` mediumint NOT NULL,
 `startDateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `endDateTime` timestamp NULL DEFAULT NULL,
 `startMileage` float(11,3) DEFAULT NULL,
 `endMileage` float(11,3) DEFAULT NULL,
 `startLatitude` float(10,8) NOT NULL,
 `startLongitude` float(11,8) NOT NULL,
 `endLatitude` float(10,8) DEFAULT NULL,
 `endLongitude` float(11,8) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


ALTER TABLE `vehicleTrip`
 ADD PRIMARY KEY (`vehicleID`,`startDateTime`) USING BTREE;
COMMIT;

也許這就是你要找的?

SELECT Day(startDateTime) As "day", 
      Month(startDateTime) As "month",
      Sum(TIMESTAMPDIFF(SECOND, startDateTime, endDateTime ))
            As totalDuration,
      count(*) As trips, 
      sum(endMileage-startMileage) As totalMleage
FROM vehicleTrip                            
WHERE vehicleID = :vehicleID
 AND vehicleEndCodeID != 1
 AND startDateTime BETWEEN :startDateTime And :endDateTime                             
Group By 2, 1
ORDER BY 2 DESC, 1 DESC

(我假設您想按月和日排序,最新的優先?)

還要考慮

GROUP BY DATE(startDateTime)
ORDER BY DATE(startDateTime) DESC

更多的

!=很難優化。我沒有看到任何避免“文件排序”的方法,但這個索引可能有助於提高性能:

INDEX(vehicleID, startDateTime)   -- in this order

但是,既然那已經是PRIMARY KEY,請不要添加 this INDEX

重新開始

現在CREATE TABLE已經添加了(這就是我經常要求的原因),這就是我將如何回答這個問題:

如果可能,請 . 這允許優化器同時進行。在您的問題中,您在每個問題中的內容並不完全相同。ORDER BY``GROUP BY

一種變體是改變方向:

GROUP BY a     , b
ORDER BY a DESC, b DESC

也是最優的。

(此處不相關:)在大多數情況下,列上的 ASC 和 DESC 的任何混合ORDER BY都會阻止ORDER BY.

我使用DATE(..)而不是兩列的建議避免了這個問題並解決了明年一月出現的潛在錯誤。但是……它可能會遇到“唯一完整的分組依據”問題,因為DAY(..), MONTH(..)它不被辨識為 `DATE(..)

為了避免上述一些混亂,我首先建議

GROUP BY 2     , 1
ORDER BY 2 DESC, 1 DESC

如果這失敗了,我會從袖子裡拿出一個子查詢。

引用自:https://dba.stackexchange.com/questions/274621