0

我有一些具有以下架构的数据表

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

知道如何做到这一点吗?

4

2 回答 2

1

尚不清楚您要更新哪一列(last_comm 或 device_ID )如果您想更新 last_comm 以获取相应的 device_id 您可以尝试使用基于连接的更新以获得最大结果

UPDATE DeviceStatuses d
INNER JOIN  (
    select source, max(Last_Comm ) max_last_comm
    from (
    select source, Last_Comm
    from  RcptStatuses
    UNION 
    select source, Last_Comm
    from  ReceivedTrans
    ) t
    group by source 
) t2 ON d.Device_Id = t2.source
SET d.Last_Comm =  t2.max_last_comm 
于 2020-07-22T16:38:50.703 回答
0

您不需要MAX(Last_Comm)从其他表中获取。只需加入其他表中的每一行Last_Comm,然后将其提升到其中的最大值。它会逐行执行此操作,但到最后,DeviceStatuses.Last_Comm将具有最大的价值。

UPDATE DeviceStatuses AS d
JOIN RcptStatuses AS rs ON d.Device_ID = rs.Source
JOIN ReceivedTrans AS rt ON d.Device_ID = rt.Source
SET d.Last_Comm = GREATEST(d.Last_Comm, rs.Last_Comm, rt.Last_Comm)

但如果DeviceStatuses.Device_ID为 NULL,我不知道您希望如何将其与其他表中的任何行匹配。

于 2020-07-22T16:50:44.810 回答