为每个ID选择最近的行

时间:2014-07-05 06:27:45

标签: mysql

我有两个表,一个是主表,第二个是详细信息表。 我需要来自详细信息表的最新行,如果详细信息表没有相应行的详细信息,那么它应显示该ID的空白行和主表信息。

我使用了以下查询,但没有提供所需的输出

select st.Station_Id,st.id,st.StationType,st.stationname,st.Latitude,st.Longitude, max  (pump.LastUpdate)

作为LastUpdate,pump.daily_abstraction,来自sgwebdb.stations的pump.water_level为st 左外连接sgwebdb.pump_station_data作为st.station_id = pump.station_id上的泵 其中st.DeletionDate为null,st.stationtype ='泵站' 按st.station_id分组;

主表 - 站

ID Station_ID StationType StationName纬度经度

1 Pump0泵站ABC 5.555 100.4578 2 Pump1泵站DEF 5.555 100.4578 3 Pump2泵站GHI 5.555 100.4578 4 Pump3泵站JKL 5.555 100.4578 5 Pump4泵站MNO 5.555 100.4578 6 Pump5泵站PQR 5.555 100.4578 7 Pump6泵站STU 5.555 100.4578 8 Pump7泵站VXY 5.555 100.4578 9 Pump8泵站ZAB 5.555 100.4578 10 Pump9泵站CDE 5.555 100.4578 11 Pump10泵站FGH 5.555 100.4578 12 Pump11泵站IJK 5.555 100.4578 13 Pump12泵站LMN 5.555 100.4578 14 Pump13泵站OPR 5.555 100.4578 15 Pump14泵站QST 5.555 100.4578 16 Pump15泵站UVW 5.555 100.4578

详细信息表名称:pump_station_data`

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

1 个答案:

答案 0 :(得分:3)

试试这个sql:

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

对于第二个请求,请尝试以下方法:
我假设您的主表为" station",该表中的station id的列名是" Station_id",

select psd.*, st.Station_id from pump_station_data as psd
right join station as st
on psd.Station_id = st.Station_id
where psd.id in  (
    select max(id) from pump_station_data group by Station_id
)
order by st.Station_id;