结合两个复杂的SQL查询

时间:2013-04-26 15:58:42

标签: mysql select join

所以我已经达到了我的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

我的目标是将它们组合成一个查询,因为它经常被调用

1 个答案:

答案 0 :(得分: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