2013-05-07 73 views
0

首先,這裏是我的數據庫是什麼樣子:結合2個複雜的MySQL查詢到一個

當前 - 表

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 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 

查詢2

SELECT MAX(h.TIME) AS LastDown 
FROM TABLENAME 
WHERE h.STATUS IN ('On-Login-Screen','IE-Window-Missing') 

的最終目標是添加一個 「最後向下」 列由該查詢返回的每一ID。我只是無法弄清楚如何去做。

+1

'MAX(情況下h.status在( '在登錄屏幕', 'IE-窗口 - 缺少'),然後小時。時間結束)' – 2013-05-07 20:20:59

+0

^^將其作爲答案,以便我可以接受它,並非常感謝你! – 2013-05-07 20:34:07

回答

2
max(case when h.status in ('On-Login-Screen','IE-Window-Missing') then h.time end) 

或者我猜你也可以把它寫

max(if(h.status in ('On-Login-Screen','IE-Window-Missing'), h.time, NULL))