我试图在mysql中选择每个组的第一行。我按照How to select the first row for each group in MySQL?
等示例进行了操作出于某种原因,这对我不起作用。有以下sql
SELECT stationID, vrID, vrsCreatedAt FROM (
SELECT VRS.stationID, VR.vrVehicleID, VRS.vrID, VRS.vrsCreatedAt FROM VehicleRoutes VR
LEFT OUTER JOIN VehicleRouteStations VRS ON VRS.vrID = VR.vrID
WHERE VR.vrRouteID = 8 AND VR.vrStatus = 'active' AND VR.vrID = 65
ORDER BY VRS.vrsCreatedAt DESC) x
结果集是
43 65 2017-02-06 17:15:14
9 65 2017-02-06 17:13:12
42 65 2017-02-06 17:09:25
41 65 2017-02-06 17:07:14
69 65 2017-02-06 17:03:58
........
42 65 2017-01-17 16:35:47
63 65 2017-01-17 14:34:57
322 65 2017-01-17 14:31:45
315 65 2017-01-17 13:53:33
当我通过statemenet应用该组时
SELECT stationID, vrID, vrsCreatedAt FROM (
SELECT VRS.stationID, VR.vrVehicleID, VRS.vrID, VRS.vrsCreatedAt FROM VehicleRoutes VR
LEFT OUTER JOIN VehicleRouteStations VRS ON VRS.vrID = VR.vrID
WHERE VR.vrRouteID = 8 AND VR.vrStatus = 'active' AND VR.vrID = 65
ORDER BY VRS.vrsCreatedAt DESC) x GROUP BY vrID
我得到了
315 65 2017-01-17 13:53:33
这不是第一行,而是最后一行。即使我尝试ORDER BY VRS.vrsCreatedAt DESC
我也会得到同样的行为。
我知道这应该可行,因为我之前使用过。也许在最新的MySQL版本5.7.17-0ubuntu0.16.04.1 (Ubuntu)
中,这不再适用了吗?
由于
答案 0 :(得分:0)
您必须在结果中明确说出您想要的内容。有多行"聚合"分成一排。
对于您分组的字段,显然会得到相同的值,因此这不是问题。必须暗示所有其他字段。你不会得到同一个领域'或类似的东西,你得到
底线是:如果您想获得特定结果,您应该不使用分组(在子查询中选择结果?)或仅对该字段使用聚合。