mysql - 如何根据同一数据库中另一个表的条件更新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
解决方案
您可以将第一个查询的结果用作子查询来取消选择行(通过使用NOT IN
)UPDATE
:
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
子查询中。
推荐阅读
- angular - 在两个活动组件之间共享单个 API 调用的 Angular 最佳实践
- oracle-apex - Oracle Apex - 如果更改一页,应用程序的用户是否必须再次登录?
- node.js - Puppeteer 错误找不到选择器的节点(按钮单击)
- php - 将桌子与 foreach 并排放置
- mysql - 如何查询工作中有字母(例如K)且薪水大于某个数字的姓名
- python - 我怎样才能总结一天的时间戳?
- javascript - 如何将源转换为我的资产 img ?角
- angular - 删除查询参数后如何防止滚动到顶部?
- wiki - 如何在 cytoscape 中打开 wikipathway(作为通路)?
- javascript - 如何在render()reactjs中定义useState变量