我有一个MySQL数据库,结构如下......
网站有很多传感器 传感器有许多SensorReadings
我想获取一个站点的所有传感器以及所有这些传感器的最后5个SensorReadings。我怀疑我将不得不对存储过程和临时表做一些事情(如果它们甚至存在于MySQL中。
答案 0 :(得分:2)
可能是Something like ......
SELECT reading,
date
FROM (select sensor_id,
reading,
date,
@num := if(@sensor_id = sensor_id, @num + 1, 1) as row_number,
@sensor_id := sensor_id as dummy
from sensor_readings
order by sensor_id,
date desc) T
WHERE row_number<=5
请在您的问题中提供您的实际表格结构。
答案 1 :(得分:1)
使用MySQL变量的完整示例。为简洁起见,这会显示每个传感器的前2个读数。
drop table if exists Sensors;
create table Sensors (Id int);
insert Sensors (id) values (1), (2), (3);
drop table if exists SensorReadings;
create table SensorReadings (SensorId int, RecordDate date);
insert SensorReadings (SensorId, RecordDate) values
(1, '2011-01-01'),
(1, '2011-01-02'),
(1, '2011-01-03'),
(2, '2011-01-01'),
(2, '2011-01-02'),
(2, '2011-01-03');
set @num = -1;
set @SensorId = -1;
select *
from Sensors s
join (
select *
, @num := if(@SensorId = SensorId, @num + 1, 1) as rn
, @SensorId := SensorId
from SensorReadings sr
order by
SensorId
, RecordDate desc
) as numbered
on numbered.SensorId = s.Id
where numbered.rn < 3;
答案 2 :(得分:0)
基于Andomar转储
select * from SensorReadings as t1
where (select count(*) from SensorReadings as t2
where t1.sensorid = t2.sensorid and t2.recordDate > t1.recordDate) <2