sql - 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”`
解决方案
您的错误消息表明您使用的是 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)
推荐阅读
- javascript - 即使我在 javascript 中应用过滤器,表数据也会保持刷新
- javascript - 使用初始文本值反应表单输入
- javascript - 鼠标事件[X 和 Y 坐标]
- sqlite - Sqlite 层次结构动态
- android - 底部像素溢出的 RenderFlex
- typescript - 如何将打字稿接口声明为类属性
- android - 关机时崩溃(可能是finishActivityAffinity)
- jenkins - Jenkins-X 和 Jenkins Helm 图表是否相同?
- sql - SQL Server:存储过程中的查询优化
- angular - 通过角度解析字符串编码