我有一些具有以下架构的数据表
DeviceStatuses Table
id, Last_Comm, Device_Id
00001, 2020-10-23, DEV1
00002, 2020-09-23, DEV2
RcptStatuses Table
id, Last_Comm, Source
R0001, 2020-10-25, DEV1
R0002, 2020-09-25, DEV2
R0003, 2020-10-30, DEV1
ReceivedTrans Table
id, Last_Comm, Source
R0001, 2020-10-25, DEV1
R0002, 2020-09-25, DEV2
R0003, 2020-10-31, DEV1
我需要使用“RcptStatuses 表的 Last_Comm”字段值和“ReceivedTrans 表的 Last_Comm”字段值中的最大值(最大值)来更新“DeviceStatuses”表的“Last_Comm”字段值。由于一些限制,我必须使用单个查询来执行此操作。
这些是预期的输出
DeviceStatuses Table (After update)
id, Last_Comm, Device_Id
00001, 2020-10-31, DEV1 (max value for DEV1 Last_Comm from RcptStatus and RecievedTx Table)
00002, 2020-09-25, DEV2 (max value for DEV2 Last_Comm from RcptStatus and RecievedTx Table)
我试过这个
UPDATE DeviceStatuses SET Last_Comm =
(SELECT MAX(lst) FROM (SELECT rsns.Last_Commu AS lst FROM RcptStatuses rsns , DeviceStatuses WHERE Device_Id = rsns.Source
UNION ALL
SELECT rtns.Last_Comm AS lst FROM ReceivedTrans rtns, DeviceStatuses WHERE Device_Id = rtns.Source ) As T)
WHERE
(SELECT MAX(lst) FROM (SELECT rsns.Last_Comm AS lst FROM RcptStatuses rsns, DeviceStatuses WHERE Device_Id = rsns.Source
UNION ALL
SELECT rtns.Last_Comm AS lst FROM ReceivedTrans rtns , DeviceStatuses WHERE Device_Id = rtns.Source ) AS T ) > Last_Comm
但这会导致所有设备的更新时间相同(设备 001 的 lastCom)。
其他需要考虑的事项:-
- DeviceId 和 Source 不是唯一的(可能在表中重复)
- 仅当 DeviceStatuses 表的 DeviceId 值小于其他表的最大值或 DeviceId 字段值为 NULL 时,才需要更新 DeviceId
- 数据库驱动是 MySQL
知道如何做到这一点吗?