首页 > 解决方案 > 如何根据同一数据库中另一个表的条件更新sql数据库表

问题描述

我在数据库中有两个表。

table_1(device_ID, date,voltage)

table_2(device_ID,device_status)

我正在尝试创建一个每 5 分钟执行一次的事件。

我想要实现的是,如果过去 10 分钟内没有新数据,则从 table_1 中选择 device_ID 并更新 table_2,这意味着将 device_status 设置为 0。

如何在两个表之间传递条件?

BEGIN 
  select device_ID from table_1 where date =  DATE_SUB(NOW(), INTERVAL 10 Minutes);                          

//here i will get device_IDs if there was a data within last 10 minutes. 

//but i need device_ID if there were no data. 

//how to update table_2 based on the above condition?

END

标签: mysqldatabasesql-update

解决方案


您可以将第一个查询的结果用作子查询来取消选择行(通过使用NOT INUPDATE

UPDATE table2
SET device_status = 0
WHERE device_ID NOT IN (select device_ID 
                        from table_1 
                        where date >  DATE_SUB(NOW(), INTERVAL 10 Minutes))

注意我认为你可能想要>,而不是=where子查询中。


推荐阅读