我的数据库中有两个表。
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
最佳答案
您可以使用第一个查询的结果作为子查询来取消选择UPDATE
的行(通过使用NOT IN
):
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
条件中使用 >
,而不是 =
。
关于mysql - 如何根据同一数据库中另一个表的条件更新sql数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57459524/