使用条件将mysql表连接到自身

时间:2012-12-09 11:28:35

标签: mysql database join

我希望有人可以帮助我。

我正在尝试在mysql中编写一个查询,我很难获得正确的语法。让我解释一下我想做什么。

我有一个表格,其中包含构造的测量数据,每个条目都有一个location_id,room_id,measurement_value,floor_num,measurement_date。我正在尝试编写一个查询来获取每层楼的最新测量数据(只有两层)。所以我在想这样的事情,但我无法让它发挥作用。

 select bottom_floor.value as bottom_value, top_floor.value as top_value
 from 
 (select measurement_value, measurement_date, floor_num, room_id from rom_measurements where location_id = '1' and floor_num='1' order by measurement_date DESC limit 1) as bottom_floor
 Join 
 (select measurement_value, measurement_date, floor_num, room_id from rom_measurements where location_id = '1' and floor_num='2' order by measurement_date DESC limit 1) as top_floor

所以我认为这会让我回到这两个价值观。我已经看到,如果两个子查询中的一个返回一个空集,则它不起作用,我也很确定我在这里做了其他错误。

有人可以推荐更好的方法来实现这一目标吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

场内所有房间的总面积:

select square, measurement_date, floor_num
from room_measurements rm
join (
  select location_id, floor_num, max(measurement_date) as date, sum(measurement_value) as square
  from room_measurements 
  group by location_id, floor_num    
) rm2 
ON rm.measurement_date=rm2.date AND rm.location_id=rm2.location_id AND rm.floor_num=rm2.floor_num
WHERE location_id = '1'

地板上每个房间的正方形:

select measurement_value, measurement_date, floor_num, room_id
from room_measurements rm
join (
  select location_id, floor_num, room_id, max(measurement_date) as date
  from room_measurements 
  group by location_id, floor_num, room_id    
) rm2 
ON rm.measurement_date=rm2.date AND rm.location_id=rm2.location_id AND rm.floor_num=rm2.floor_num AND rm.room_id = rm2.room_id
WHERE location_id = '1'