有没有一种方法可以合并以下两个语句,使我只写一次UPDATE表?该表的名称为STAT_SEP。
UPDATE STAT_SEP LEFT JOIN calendar on STAT_SEP.`Period` = calendar.`Unique_Period`
SET
STAT_SEP.First_Date = calendar.First_Date;
UPDATE STAT_SEP
, (SELECT First_Date AS earliest_date FROM STAT_SEP ORDER BY First_Date ASC LIMIT 1) fancy_alias
SET `Index` = TIMESTAMPDIFF(MONTH, earliest_date, First_Date);
答案 0 :(得分:0)
您可以在子查询中计算最早的日期,然后将其用于更新:
UPDATE STAT_SEP s LEFT JOIN
Calendar c
ON s.`Period` = c.`Unique_Period` CROSS JOIN
(SELECT MIN(c2.First_Date) as earliest_date
FROM STAT_SEP s2 JOIN
Calendar c2
ON s2.Period = c.unique_period
) c2
SET s.First_Date = c.First_Date,
s.Index = TIMESTAMPDIFF(MONTH, c2.earliest_date, c.First_Date);