sql在单独的表中减去相应的元素

cunj1qz1  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(331)

所以我有两个表,都共享键“product id”,例如,我需要减去它们匹配的地方

Table 1
Key    Value
1       70
2       50
3       12
4       5
5       18
Table 2
Key    Value
2       5
3       3
4       1
5       1

我需要输出

Output
Key    Value
1       70
2       45
3       9
4       4
5       17

我试过了

Update Table1
Set Table1.Count = Table1.Count - (
Select Table2.Count
From Table2
Where Table2.ID = Table2.ID
);

但这会将键1的值设置为null
我还尝试在where之前添加一个连接,但这给了我一个错误:
ora-01427:单行子查询返回多行ora-06512:位于“sys.dbms\u sql”`

mctunoxg

mctunoxg1#

您的错误消息表明您使用的是oracle,而不是您标记的mysql。
查询问题:
suqbuery中的关联子句错误: Table2.ID = Table2.ID 中所有行成功 table2 ,并因此返回多行,因此会出现错误
您需要处理子查询不返回任何行的情况,否则 null 值传播到您的更新: coalesce() 可用于此
考虑:

update table1 
set count = count - coalesce(
    (select t2.count from table2 t2 where t2.id = table1.id),
    0
);

或者,或者:

update table1 
set count = (select t2.count from table2 t2 where t2.id = table1.id)
where exists (select 1 from table2 t2 where t2.id = table1.id)
ht4b089n

ht4b089n2#

你可以用 LEFT JOIN 包括 COALESCE 函数以更新不匹配的记录,同时防止出现空值:

UPDATE Table1 t1
   LEFT JOIN Table2 t2 ON t1.Id = t2.Id
    SET t1.Count = Coalesce(t1.Count,0) - Coalesce(t2.Count,0)

mysql案例演示
更新:似乎这个问题是重新标记甲骨文。那么你可以用这样的 MERGE 声明:

MERGE INTO Table1 t1 
USING Table2 t2 
ON (t1.Id = t2.Id)
    WHEN MATCHED THEN
        UPDATE SET t1.Count = Coalesce(t1.Count,0) - Coalesce(t2.Count,0)

oracle案例演示 Coalesce() 可能被替换为 Nvl() 用于oracle数据库。

相关问题