我希望有人能帮助我。
我正在尝试在 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
所以我认为这会给我返回两个值。我已经看到,如果两个子查询之一返回一个空集,它就不起作用,而且我也很确定我在这里做错了其他事情。
有人可以推荐一种更好的方法来实现这一目标吗?
谢谢!
最佳答案
地板上所有房间的总面积:
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'
关于mysql - 使用条件将 mysql 表连接到自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13786973/