以下是我如何在一个语句中完成所有这些工作。(请注意,此查询假定它idtanklevel
是表中的 PRIMARY KEY 或至少一个 UNIQUE KEY tanklevel2
;如果不是这种情况,则需要调整查询。)
一些简短的评论来记录每个表引用和每个内联视图的目的:
-- m = get id of latest row
-- t = get latest row (the row to be updated)
-- pr = get id for the prior row
-- pri = source for prior row id
-- l = id of latest row (identical to "m")
-- pv = get value from prior row
-- p = wrapper so we can join to row returned from pv
UPDATE fw_db.tanklevel2 t
JOIN ( SELECT MAX(idtanklevel) AS idtanklevel FROM fw_db.tanklevel2 ) m
ON m.idtanklevel = t.idtanklevel
CROSS
JOIN ( SELECT pv.glycolsmall
, pv.idtanklevel
FROM ( SELECT MAX(pri.idtanklevel) AS idtanklevel
FROM fw_db.tanklevel2 pri
WHERE pri.idtanklevel <
(SELECT MAX(l.idtanklevel) FROM fw_db.tanklevel2 l)
) pr
JOIN fw_db.tanklevel2 pv
ON pv.idtanklevel = pr.idtanklevel
LIMIT 1
) p
SET t.glycolsmallchange = ROUND(t.glycolsmall - p.glycolsmall,2)
请注意,上面的查询使用稍微不同的技术来识别“先前”行。查询不是从最大 id 值中减去 1,而是获取第二高的 id 值(低于最大值的最高 id 值)。
要实现您的查询使用的相同策略(即从最大 id 值中减去 1,请删除上面该查询的这一部分:
FROM ( SELECT MAX(pri.idtanklevel) AS idtanklevel
FROM fw_db.tanklevel2 pri
WHERE pri.idtanklevel <
(SELECT MAX(l.idtanklevel) FROM fw_db.tanklevel2 l)
) pr
并将其替换为:
FROM ( SELECT MAX(l.idtanklevel)-1 AS idtanklevel
FROM fw_db.tanklevel2 l
) pr
要在不实际执行更新的情况下测试此语句,请删除SET
子句并将UPDATE
关键字替换为SELECT
和相关表达式列表,以便您查看返回的行,例如:
SELECT t.glycolsmallchange AS old_glycolsmallchange
, ROUND(t.glycolsmall - p.glycolsmall,2) AS new_glycolsmallchange
, t.idtanklevel AS latest_row_id
, t.glycolsmall AS latest_glycolsmall
, p.idtanklevel AS prior_row_id
, p.glycolsmall AS prior_glycolsmall
FROM