Mysql查询以获取给定项目编号的最近2个

Mysql查询以获取给定项目编号的最近2个,sql,mysql,Sql,Mysql,我的数据库中有以下属性 统计id、devicename、值、时间戳 对于给定的统计信息,我想为每个唯一的设备查找最近的2个时间戳和相应的提示值 我在尝试像这样的东西 试验1 select statistic, devicename, value, timestamp from X_STATSVALUE where statistic=19 order by orgtime DESC limit 2; 这给了我前2个时间戳,但不是每个设备 试验2 select statistic, device

我的数据库中有以下属性

统计id、devicename、值、时间戳

对于给定的统计信息,我想为每个唯一的设备查找最近的2个时间戳和相应的提示值

我在尝试像这样的东西

试验1

select statistic, devicename, value, timestamp
from X_STATSVALUE
where statistic=19
order by orgtime DESC limit 2;
这给了我前2个时间戳,但不是每个设备

试验2

select statistic, devicename, value, timestamp
from X_STATSVALUE as x 
where x.statistic=241
  and (select count(*)
       from X_STATSVALUE as y
       where y.statistic=x.statistic
         and y.device=x.device
         and y.timestamp > x.timestamp) <=1;
但这也不太管用


基本上,我想要2个最新的时间戳,每个设备的值,对于给定的统计。。非常感谢您的帮助:

这就是我解决此类问题的方法:

SELECT x.statistic, x.devicename, x.value, x.timestamp
FROM X_STATSVALUE AS x
  LEFT OUTER JOIN X_STATSVALUE AS x2
    ON (x.statistic = x2.statistic 
    AND x.devicename = x2.devicename 
    AND x.timestamp < x2.timestamp)
GROUP BY x.statistic, x.devicename
HAVING COUNT(*) < 2;
换言之,显示行以使具有相同统计信息和devicename以及更大最近时间戳的其他行少于两行

我假设给定统计信息和设备名称的时间戳列中不会有重复项。

请尝试以下方法:

SELECT DISTINCT x.statistic, x.devicename, x.value, x.timestamp
FROM X_STATSVALUE AS x
WHERE x.timestamp IN (SELECT timestamp
                      FROM X_STATSVALUE
                      WHERE devicename = x.devicename AND statistic = x.statistic
                      ORDER BY timestamp LIMIT 2)

虽然在旧的MySQL中可能无法工作,但我在我的系统上用一个类似于您的演示表测试了以下查询,并且它可以工作。我考虑的是组织时间而不是时间戳。。您可以根据需要进行相同的名称更改

    select t1.statistic, devicename, value, timestamp from X_STATSVALUE as t1 

    inner join 

    ( select statistic, max(orgtime) as orgtime from X_STATSVALUE group by statistic ) 
as t2 

    on t1.statistic = t2.statistic and t1.orgtime = t2.orgtime

    UNION

    select tb1.statistic, tb1.devicename, tb1.value, tb1.timestamp
    from X_STATSVALUE as tb1 inner join 

    ( select statistic, max(orgtime) as orgtime from X_STATSVALUE  WHERE statistic+orgtime not in 
    (select t1.statistic+t1.orgtime from X_STATSVALUE as t1 inner join 
    ( select statistic, max(orgtime) as orgtime from X_STATSVALUE group by statistic ) 
as t2 on t1.statistic = t2.statistic and t1.orgtime = t2.orgtime
    ) group by statistic 
    ) 

    as tb2 on tb1.statistic = tb2.statistic and tb1.orgtime = tb2.orgtime

这只适用于MySQL。其他RDBMS会告诉您,您不能只根据所选语句的一部分进行分组,而必须根据所有四个语句进行分组