MySQL LEFT JOIN日期与订单

时间:2014-04-18 07:56:43

标签: mysql sql date join left-join

我有以下表格:

sensors:

id  name  key   code
1   s1    abc   123
2   s2    def   456
3   s3    ghi   789

measurements:

id value sensor_id generated_at
1  1.0   1         2013-12-30 06:00:00
2  1.0   1         2013-12-30 06:01:00
3  1.0   1         2013-12-30 06:02:00
4  3.0   2         2013-12-30 07:00:00
5  3.0   2         2013-12-30 07:01:00
6  3.0   2         2013-12-30 07:05:00
7  5.0   3         2013-12-30 08:02:00
8  5.0   3         2013-12-30 08:03:00
9  5.0   3         2013-12-30 08:11:00
10 5.0   3         2013-12-30 08:15:00

我想要做的是生成包含所有传感器数据的报告,并包括接收测量的第一个和最后generated_at时间,因此MySQL请求的结果应如下所示:

id name key code first_value_generated_at last_value_generated_at
1  s1   abc 123  2013-12-30 06:00:00      2013-12-30 06:02:00
2  s2   def 456  2013-12-30 07:00:00      2013-12-30 07:05:00
3  s3   ghi 789  2013-12-30 08:02:00      2013-12-30 08:15:00

感谢您的帮助,谢谢。

5 个答案:

答案 0 :(得分:2)

我认为LEFT JOIN在这里确实是必要的(仅限于sensors.idmeasurements.sensor_id更多或更少的情况。 SQL 查询如下:

SELECT
    s.id,
    s.name,
    s.key,
    s.code,
    m.first_value_generated_at,
    m.last_value_generated_at
FROM sensors s JOIN 
   (SELECT
      sensor_id,
      MIN(generated_at) as first_value_generated_at,
      MAX(generated_at) as last_value_generated_at
    FROM
      measurements
    GROUP BY
      sensor_id
   ) m ON s.id = m.sensor_id
ORDER BY
    s.id

答案 1 :(得分:1)

我希望这对你有用,

select *
    ,(select min(generated_at) from measurements as a where a.sensor_id =s.id) as first_value_generated_at 
    ,(select max(generated_at) from measurements as b where b.sensor_id =s.id) as last_value_generated_at
 from sensors as s

答案 2 :(得分:0)

也许这可以做到 - 嵌套选择?

        select sensors.id, sensors.name, sensors.key, sensors.code,
     ( select generated_at from measurements order by time asc limit 1 )
 as first_value_generated_at,
     ( select generated_at  from measurements order by time desc limit 1 )
 as last_value_generated_at from sensors

答案 3 :(得分:0)

尝试此查询,它将生成您需要的确切输出

    select s.id,s.name,s.key,s.code,min(m.generated_at) first_vaue_generated_at,max(m.generated_at) last_value_generated_at
      from sensors s
 LEFT JOIN measurements m ON (s.id = m.sensor_id)
  group by 1,2,3,4;

答案 4 :(得分:0)

试试这个会起作用

select s.id,s.name,s.key,s.code,m.generated_at as first_value_generated_at,ml.generated_at as last_value_generated_at from sensors as s,measurements as mf,measurements as ml where s.id = mf.sessor_id and s.id = ml.sensor_id and mf.generated_at < ml.generated_at group by mf.sensor_id