我正在尝试在2列上使用GROUP BY获取我的表的所有结果并获得最后一次插入。
“价格”表:
我的要求:
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行,但错误的行,因为最后在我的DB -_-'
中创建请帮帮我!!! > _<'
THX
答案 0 :(得分:2)
由于您在station_id
子句中选择了特定WHERE
,因此您无需在GROUP BY
中添加该ON
。
子查询必须返回您正在分组的列,然后您必须将它们包含在GROUP BY
子句中。
您在外部查询中不需要JOIN
,因为fuel_id
应确保每个created_at
只有一行(除非有重复的fuel_id
对于相同的station_id
和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
)。
KeyError: ('user rating score', 'occurred at index title')