我需要更新一个表,但要获得新值,我似乎需要创建一个临时表。原因是我需要计算sum
. max
我可以做吗?
伪代码如下所示:
UPDATE users u SET usersContribution = [CREATE TEMPORARY TABLE IF NOT EXISTS tmpTbl3 AS
(SELECT ROUND(max(zz.zachetTimestamp - d.answerDate)) as answerDateDiff
FROM zachet zz
JOIN discussionansw d ON d.zachetid=zz.zachetId and d.usersid=zz.usersId and
zz.zachetTimestamp > d.answerDate
WHERE zz.whoTalk=u.userid and
NOT EXISTS (SELECT * FROM discussionansw
WHERE zachetid=zz.zachetId and usersid=u.userid')
GROUP BY zz.zachetId)]
SELECT SUM(answerDateDiff) FROM tmpTbl3;"
我使用方括号来显示必须完成的部分,但被 UPDATE 查询忽略...
我两者都有max
,sum
而且我看不到避免 tmp 表的方法。但如果可以的话,我们会很高兴有这样的解决方案。
我把答案放在这里,我在@flaschenpost 和这篇文章的帮助下得到了答案:SQL 更新到其连接值的总和
CREATE TEMPORARY TABLE IF NOT EXISTS t0tmpTbl3 AS
(SELECT zz.whoTalk, ROUND(max(zz.zachetTimestamp - d.answerDate)) as answerDateDiff
FROM zachet zz
JOIN discussionansw d ON d.zachetid=zz.zachetId and d.usersid=zz.usersId and
zz.zachetTimestamp > d.answerDate
WHERE
NOT EXISTS (SELECT * FROM discussionansw WHERE zachetid=zz.zachetId and usersid=zz.whoTalk)
GROUP BY zz.zachetId);
UPDATE users u
JOIN (SELECT whoTalk, SUM(answerDateDiff) sumAnswerDateDiff
FROM t0tmpTbl3 GROUP BY whoTalk) t
ON u.usersId=t.whoTalk
SET u.usersContribution=sumAnswerDateDiff;