2017-06-15 98 views
0

我想通過2列的GROUP BY獲取我的表的所有結果並獲取最後一次插入。MYSQL - GROUP BY 2 COLUMN ORDER BY創建日期

「價格」 表:

enter image description here

我的要求:

SELECT DISTINCT p.* 
FROM prices p 
JOIN (
SELECT MAX(created_at) as "last_created" 
FROM prices 
WHERE station_id = 27210003 
GROUP BY station_id, fuel_id) as sub 
ON sub.last_created = p.created_at 
WHERE p.station_id = 27210003 
GROUP BY p.station_id, p.fuel_id 

結果是3線,但錯了行,因爲不是我的數據庫最後創建-_-」

enter image description here

請幫幫我!!! > _ <'

THX

回答

2

既然你的WHERE子句中選擇特定station_id,你並不需要包括在GROUP BY

子查詢必須返回要分組的列,然後必須將它們包含在ON子句中。

而且你不需要GROUP BY在外部查詢,因爲JOIN應確保有隻有一行每個fuel_id(除非有相同fuel_idstation_id重複created_at)。

SELECT DISTINCT p.* 
FROM prices p 
JOIN (
    SELECT fuel_id, MAX(created_at) as "last_created" 
    FROM prices 
    WHERE station_id = 27210003 
    GROUP BY fuel_id) as sub 
ON sub.last_created = p.created_at AND sub.fuel_id = p.fuel_id 
WHERE p.station_id = 27210003 
+0

似乎不太可能有不止一個,但我們走了。 – Strawberry

+0

如果可以的話,您不僅需要使用'GROUP BY fuel_id',還需要另一列'MAX'或'MIN'來選擇您想要的。 – Barmar