2013-05-07 75 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))