mysql - 将 2 个复杂的 mysql 查询合并为一个

标签 mysql if-statement

首先这是我的数据库的样子:

当前 -- 表格

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 添加“Last Down”列。我只是不知道该怎么做。

最佳答案

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

关于mysql - 将 2 个复杂的 mysql 查询合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16427780/

相关文章:

mysql - 分区表,每个分区位于我的硬盘上的不同磁盘上

mysql - 通过 MySQL 访问 Drizzle 数据库

php - "annotations"在Doctrine中有什么优点?

cocoa-touch - Xcode 提示使用 Swift 和 Xcode 6 的 if 语句结构

c - 为什么这个 if 语句需要括号?

Mysql 查询以检查 combo_item 的所有 sub_items 是否处于事件状态

mysql - 在 mysql 池中使用回滚

MySQL热门搜索查询,如果搜索已经存在,如何添加到计数而不是插入新?

if-statement - 为什么我在 Scratch 中的 if-then 语句永远不会触发?

jquery - jQuery 中的 If-then 语句