如何在脚本上使用左连接更新表。我正在使用DB2数据库。
我创建了一个select语句,它可以工作:
**
select t1.estrcd as "transaction code",
t1.espyno as "payer",
t1.escuno as "customer no",
t1.escino as "invoice no",
t1.esvono as "voucher no",
t1.escuam as "foreign currency amount",
COALESCE(t2."received_amount",0) as "received amount",
t1.escuam + COALESCE(t2."received_amount",0) as "outstanding amount"
from m3edbedu.fsledg t1 left join
(select espyno, escino, sum(escuam) as "received_amount" from m3edbedu.fsledg
where estrcd = 20 group by espyno, escino) as t2 on
t2.espyno = t1.espyno and t2.escino = t1.escino
where t1.esreco = 0 and t1.estrcd = 10 and (t1.escuam + COALESCE(t2."received_amount",0)) = 0
order by t1.espyno, t1.escino, t1.estrcd;
**
但现在他们要求我更新表并将t1.esreco设置为9.我尝试使用以下脚本进行更新,但是我收到了错误。
update m3edbedu.fsledg t1 LEFT JOIN(select espyno, escino, sum(escuam) as "received_amount"
from m3edbedu.fsledg
where estrcd = 20
group by espyno, escino) as t2
on t2.espyno = t1.espyno and t2.escino = t1.escino set t1.esreco = 9 where t1.esreco = 0 and t1.estrcd = 10 and (t1.escuam + COALESCE(t2."received_amount",0)) = 0 order by t1.espyno, t1.escino, t1.estrcd;1;
错误:SQL0199 - 不期望关键字LEFT。有效令牌:SET。 (状态:37000,本机代码:FFFFFF39)错误:SQL0104 - 令牌1不是 有效。有效令牌:(CL END GET SET CALL DROP FREE HOLD LOCK OPEN 随着开始。 (州:37000,土着法典:FFFFFF98)
我希望有人可以帮助我。
提前致谢。 :)
答案 0 :(得分:1)
由于这是DB2数据库,因此无法在update语句中指定FROM子句。更新了答案以反映您必须做的事情(请记住,这绝不是优化的)。
update
m3edbedu.fsledg t1
set
t1.esreco = 9
where
t1.esreco = 0 and t1.estrcd = 10 and
exists(select t2.espyno
from m3edbedu.fsledg t2
where t2.estrcd = 20 and t2.espyno = t1.espyno and t2.escino = t1.escino)
and (t1.escuam + coalesce(
(select sum(t2.escuam)
from m3edbedu.fsledg t2
where t2.estrcd = 20 and t2.espyno = t1.espyno and t2.escino = t1.escino), 0) = 0)
答案 1 :(得分:0)
DB2不支持UPDATE
语句中的连接,因此您必须执行一种解决方法,例如将连接部分作为相关子查询,如下所示:
UPDATE m3edbedu.fsledg update
SET esreco = 9
WHERE EXISTS (
SELECT 1
FROM m3edbedu.fsledg t1
LEFT JOIN(
SELECT espyno,
escino,
sum(escuam) as received_amount
FROM m3edbedu.fsledg
WHERE estrcd = 20
GROUP BY espyno, escino
) as t2
ON t2.espyno = t1.espyno
AND t2.escino = t1.escino
WHERE t1.unique_key1 = update.unique_key1
AND t1.unique_key2 = update.unique_key2
AND t1.unique_key3 = update.unique_key3
--etc
AND t1.esreco = 0
AND t1.estrcd = 10
AND (t1.escuam + COALESCE(t2.received_amount,0)) = 0
)
您可能希望通过将UPDATE
部分更改为SELECT
来检查并确保从子查询中获取正确的列。
答案 2 :(得分:-1)
请改为尝试:
update t1
SET t1.esreco = 9
from m3edbedu.fsledg t1
LEFT JOIN ( select espyno, escino, sum(escuam) as "received_amount"
from m3edbedu.fsledg
where estrcd = 20
group by espyno, escino) as t2
on t2.espyno = t1.espyno
and t2.escino = t1.escino
where t1.esreco = 0
and t1.estrcd = 10
and (t1.escuam + COALESCE(t2."received_amount",0)) = 0 ;