这可能是一个梦想,但我试图让这两个单独工作的命令,作为一个单一的命令。而不是XXXXX,我想在select语句中转储(这给了我昨天的总数和今天总数的差异)。组合命令将找到最近的行(max idtanklevel)并使用它自身和前一行的差异来更新它。
update fw_db.tanklevel2 T3
inner join (select max(idtanklevel) as idtanklevel from fw_db.tanklevel2) T4
on T3.idtanklevel = T4.idtanklevel
set glycolsmallchange = XXXXX;
和
select round(sum((T1.glycolsmall) - (T2.glycolsmall)),2)
from fw_db.tanklevel2 T1, fw_db.tanklevel2 T2
where
T1.idtanklevel = (select max(idtanklevel) from fw_db.tanklevel2)
and
T2.idtanklevel=(select max(idtanklevel)-1 from fw_db.tanklevel2);
提前致谢。
答案 0 :(得分:0)
以下是我将如何在一个声明中完成所有这些工作。 (请注意,此查询假定idtanklevel
是PRIMARY 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值(低于最大值的最高id值),而不是从最大id值中减去1。
要实现您的查询使用的相同策略(即从最大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