2013-04-26 142 views
0

所以我來到我的SQL實力的絕對限制,我不能爲我的生活結合這兩個查詢,首先這裏是我的數據庫看起來像組合兩個複雜的SQL查詢

電流 - 表

ID - Unique identifier for device (Int) 
Location -Unique identifier for name of area (VarChar) 
Status - The current status of the device (VarChar) 
Time - DateTime of when the last connection was made to the device (DateTime) 

歷史

CID (Sorta unused, just as an AI field to store multiple old bits of data uniquely) (Int) 
ID - Unique identifier for device (Int) 
Location --Unique identifier for name of area (VarChar) 
Status - The current status of the device (VarChar) 
Time -- DateTime of when the last connection was made to the device (DateTime) 

因此,與在座各位說的這兩個查詢:

查詢1:

SELECT *, if(HOUR(TIMEDIFF(NOW(), TIME)) >=1, 1, 0) as OlderThanAnHour 
FROM Current 
WHERE Location like "MyLocation" 

查詢2:

SELECT ID, min(time), (abs(timestampdiff(HOUR,NOW(),TIME))/count(*)*100) as percentage 
from Historical 
where LOCATION like "MyLocation" 
group by ID 

我的目標是將它們組合成一個單一的查詢,因爲這將是通常被稱爲

+0

你是什麼意思的結合? – boisvert 2013-04-26 16:05:56

+1

目前,百分比本質上是一個隨機值,因爲它是'TIME'上的函數,而不是'TIME'的聚合函數 - 是否應該使用'min(TIME)'? – 2013-04-26 16:06:16

+0

不,它應該使用從前面選擇的min(TIME)... – 2013-04-26 16:09:29

回答

3

嘗試:

SELECT c.*, 
     if(HOUR(TIMEDIFF(NOW(), c.TIME)) >=1, 1, 0) as LatestOlderThanAnHour, 
     min(h.time) as EarliestTime, 
     (abs(timestampdiff(HOUR,NOW(),min(TIME)))/count(*)*100) as percentage 
FROM Current c 
JOIN Historical h on c.ID = h.ID 
WHERE c.Location like "MyLocation" 
group by c.ID 
+0

而且我們有一個贏家。 – 2013-04-26 16:19:46

+0

這是一些非常好的工作,我想讓你知道,我真的很感謝這方面的幫助。 – 2013-04-26 16:20:10

+0

很高興我能幫到你。 :) – 2013-04-26 16:20:38