简体   繁体   English

为表上的每个组选择最后一个时间戳(记录)

[英]Select last timestamp (record) for each group on table

I've passed through some questions here in Stack Overflow, but after some tests it's was not possible to solve my problem. 我已经在Stack Overflow中通过了一些问题,但是经过一些测试后,无法解决我的问题。 I have a table like below. 我有一张下面的桌子。

  ID           log_device_id           device_timestamp
=========================================================
  1456              0056              2019-05-19 11:45:18
  1451              0061              2019-05-19 22:00:03
  1450              0035              2019-05-19 17:16:23
  1449              0011              2019-05-19 12:31:34
  1448              0124              2019-05-18 09:11:27

I'm using the code below to get the Device ID list and timestamp; 我正在使用下面的代码来获取设备ID列表和时间戳;

sql ='SELECT log_device_id,max(device_timestamp) FROM devicetable group by log_device_id';
    $result = mysqli_query($conection, $sql);
         if (mysqli_num_rows($result) > 0) {
            while($row = mysqli_fetch_assoc($result)) {
            echo $row['log_device_id'];
            echo $row['device_timestamp'];
            }

The problem is, the result of this query returns the ID and Last Timestamp, but the $row['device_timestamp'] , comes empty and shows a 500 error. 问题是,此查询的结果返回ID和上次时间戳,但是$row['device_timestamp']空并显示500错误。

The intention of this code is to check every hour the last timestamp of each device and check if it's is offline. 此代码的目的是每小时检查每个设备的最后时间戳,并检查它是否处于脱机状态。

Thank you. 谢谢。

Here's one idea: 这是一个主意:

sql ='SELECT log_device_id,max(device_timestamp) as max_device_timestamp FROM devicetable group by log_device_id';
$result = mysqli_query($conection, $sql);
     if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
        echo $row['log_device_id'];
        echo $row['max_device_timestamp'];
        }

You set alias for max(device_timestamp) then you get value of it 您为max(device_timestamp)设置别名,然后获取它的值

$sql ='SELECT log_device_id, device_timestamp FROM devicetable WHERE device_timestamp = (SELECT MAX(device_timestamp) FROM devicetable) group by log_device_id';
$result = mysqli_query($conection, $sql);
if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo $row['log_device_id'];
        echo $row['device_timestamp'];
    }
}

Hopefully this will work for you. 希望这对您有用。 Thank You. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM