简体   繁体   English

结合两个复杂的SQL查询

[英]Combining two complex SQL queries

So I've arrived at the absolute limit of my sql prowess and I can't for the life of me combine these two queries, First off here's what my database looks like 因此,我已经达到了sql能力的绝对极限,并且我一生无法将这两个查询结合起来,首先,这是数据库的外观

Current - Table 当前-表

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)

Historical 历史的

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)

So with that all said here's the two queries: 因此,这就是两个查询:

Query 1: 查询1:

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

Query 2: 查询2:

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

My goal is to combine them into a single query, since it's going to be called often 我的目标是将它们组合成一个查询,因为它将经常被调用

Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM