2012-12-09 33 views
0

我希望有人可以幫助我在這裏。加入一個mysql表格到自己的標準

我想寫一個查詢在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

的地板上的客房總面積:

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' 
+0

越來越近,但我得到的各樓層多個結果。我希望能得到兩排,一個用於頂層,一個用於底層。沒有更多... – ackerchez

+0

房間呢?你需要總結地板上所有房間的測量結果嗎? – alex

+0

好的,嘗試兩種變體,我已經編輯了答案。 如果它現在可以工作,給我測試數據。 – alex