1

結果の「user_id」は、Locationテーブルの最初のレコードに降順で対応するものになると思います。しかし、最初のレコードの「user_id」を昇順またはID順で取得しています。

SELECT Device.name, Location.user_id
  FROM    locations Location
       LEFT JOIN devices Device
            ON Device.id = Location.device_id
 WHERE Device.id IN (491)
GROUP BY Location.device_id
ORDER BY Location.location_datetime DESC

誰もが理由を知っていますか?それを改善する方法は?

ありがとう!

4

2 に答える 2

2

You could use something like this:

SELECT
  devices.name,
  (select locations.user_id
   from locations
   where locations.device_id = devices.id
   order by locations.location_datetime desc
   limit 1)
FROM
  devices
WHERE
  device.id = 491

you can't use group by with nonaggregated columns to get the first or the last record: it is not guaranteed that it will always work.

EDIT: if you need to select more than one field from locations, you could use this:

SELECT l1.*, devices.name
FROM
  locations l1 inner join
  (select device_id, max(location_datetime) as maxdt
   from locations
   group by device_id) l2
  on l1.device_id = l2.device_id and l1.location_datetime=l2.maxdt
  left join devices
  on devices.id = l1.device_id

this query will select last location for each device_id. If there are more than one location with the same maximum datetime, this query will return each one. If you need just one, and don't mind which one is selected, you could also add a GROUP BY l1.device_id clause at the end.

于 2012-12-10T14:29:38.753 に答える
0

これを試して

      SELECT Device.name, Location.user_id ,Location.location_datetime
      FROM    locations Location
      LEFT JOIN devices Device
        ON Device.id = Location.device_id
     WHERE Device.id IN (491)

    ORDER BY Location.user_id DESC
    GROUP BY Location.device_id
于 2012-12-10T14:20:29.810 に答える