gpt4 book ai didi

mysql - 组合两个复杂的 SQL 查询

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:16 25 4
gpt4 key购买 nike

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

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

最佳答案

尝试:

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

关于mysql - 组合两个复杂的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16240612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com