MySQL - 如何检索按其中一个字段分组的最后记录值?

时间:2014-07-03 06:44:46

标签: mysql sql

我有一张表node_weather,如下所示:

+--------------------+--------------+------+-----+--------------------+
| Field              | Type         | Null | Key |                    |
+--------------------+--------------+------+-----+--------------------+
| W_id               | mediumint(9) | NO   | PRI | ement              |
| temperature        | int(10)      | YES  |     |                    |
| humidity           | int(10)      | YES  |     |                    |
| wind_direction     | int(10)      | YES  |     |                    |
| wind_speed         | int(10)      | YES  |     |                    |
| wet_temperature    | int(10)      | YES  |     |                    |
| P_id               | mediumint(9) | YES  | MUL |                    |
| time               | timestamp    | NO   |     | CURRENT_TIMESTAMP  |
| level_current      | int(10)      | YES  |     |

在此表中,我正在记录来自4个不同气象站的数据,由P_id字段定义(=> P_id可以是值1,2,3或4)。来自所有电台的数据不断填满表格。

如何创建查询以获取每个气象站的最后记录行?

3 个答案:

答案 0 :(得分:2)

也许是这样的:

SELECT
    *
FROM
    node_weather
JOIN
(
    SELECT
        tblInner.P_id,
        MAX(tblInner.time) AS maxTime
    FROM
        node_weather as tblInner
    GROUP BY
        tblInner.P_id
) AS tblMax 
    ON tblMax.maxTime = node_weather.time 
    AND tblMax.P_id = node_weather.P_id

这将获得最新timeP_id

的组合

答案 1 :(得分:1)

尝试此查询。它比子查询更快..

select nw1.* from node_weather nw1
LEFT JOIN node_weather nw2 on nw2.P_id = nw1.P_id and nw2.time>nw1.time
where nw2.W_ID is null;

答案 2 :(得分:0)

SELECT * FROM node_weather GROUP BY P_id ORDER BY time DESC

应该做的伎俩