首页 > 解决方案 > SQL 在单独的表中减去相应的元素

问题描述

所以我有 2 个表,都共享密钥“产品 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
);

但这会将 Key 1 的值设置为 null

我也尝试在 Where 之前加入一个连接,但这给了我错误:

ORA-01427:单行子查询返回多于一行 ORA-06512:在“SYS.DBMS_SQL”`

标签: sqloraclejoinselectsql-update

解决方案


您的错误消息表明您使用的是 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)

推荐阅读