每个id的最近行

时间:2014-09-03 04:01:40

标签: mysql

我有一张下表,我需要每个id的最新行。

------------------------------------------------------------------------
id    Station_id      lastupdate       hrl_abst daily_abst Water_Level
------------------------------------------------------------------------
3      Pump15    2014-05-13 12:45:00    23            45      8
4      Pump0     2014-05-20 01:01:00    1             1       1
5      Pump0     2014-07-02 12:00:00    15.41      15.41     51.95
6      Pump0     2014-07-03 12:00:00    0.9         21.6     26.65
7      Pump1     2014-07-03 01:30:00    0            0       21.69
8      Pump0     2014-07-05 09:20:00    20           20      26.7535
9      Pump1     2014-07-05 11:25:00    20           20      21.69
10     Pump2     2014-07-05 15:10:00    20           20      9.4287
11     Pump3     2014-07-05 15:45:00    20           20      6.2608
12     Pump4     2014-07-05 13:25:00    20           20      2.2636
13     Pump5     2014-07-05 16:31:00    20           20      2.2832
14     Pump6     2014-07-05 16:38:00    20           20      2.1249
15     Pump7     2014-07-05 17:35:00    20           20      10
16     Pump8     2014-07-05 17:35:00    20           20      10
17     Pump9     2014-07-05 19:36:00    20           20      2.0994
18     Pump10    2014-07-05 19:55:00    20           20      2.112
19     Pump11    2014-07-05 20:15:00    20           20      2.1054
20     Pump12    2014-07-05 19:45:00    20           20      2.099
21     Pump13    2014-07-05 18:45:00    20           20      2.0994
22     Pump14    2014-07-05 16:45:00    20           20      10
23     Pump15    2014-07-05 16:45:00    20           20      2.1234
24     Pump16    2014-07-05 19:45:00    20           20      10
25     Pump17    2014-07-05 18:25:00    20           20      52.5678
26     Pump18    2014-07-05 18:50:00    20           20      42.0116
27     Pump19    2014-07-05 14:20:00    20           20      10
---------------------------------------------------------------------

我使用了以下查询,但它无效。

 select * from sgwebdb.pump_station_data
  where id in  (
  select max(id) from sgwebdb.pump_station_data group by Station_id
   )
 order by Station_id;

3 个答案:

答案 0 :(得分:2)

<强> QUERY

SELECT *
FROM sgwebdb.pump_station_data t1
INNER JOIN
(
  SELECT Station_id,  MAX(lastupdate) as lastupdate
  FROM sgwebdb.pump_station_data
  GROUP BY Station_id
) t2
  ON t1.Station_id = t2.Station_id
  AND t1.lastupdate = t2.lastupdate

答案 1 :(得分:0)

您需要在子查询中仅选择id而不是max id

 select * from pump_station_data
where id in (
select id from pump_station_data group by Station_id order by lastupdate desc
)

这是SQL FIDDLE

答案 2 :(得分:0)

<强> QUERY

SELECT * FROM sgwebdb.pump_station_data 
ORDER BY `lastupdate` DESC, `id` DESC 
GROUP BY `Station_id`

这将通过最新的id和最新的'lastupdate'

为您提供订单