注意 :这不是作业。我已将我的情况简化为通用表格。
所以我有两张桌子。表1和表2 table1中的VALUE1是我想要设置的 计算为 VALUE1 =苹果(VALUE2)-Oranges(VALUE3)
TABLE1
ID INT //PRIMARY KEY
VALUE1 INT
VALUE2 INT //FOREIGN KEY TO TABLE2
VALUE3 INT //FOREIGN KEY TO TABLE2
TABLE2
ID INT //PRIMARY KEY
APPLES INT
ORANGES INT
这让我想到了这个问题。如何使用Co相关子查询进行更新?
这是我试过的,
它执行时没有错误,但值保持不变。我觉得很奇怪。
UPDATE TABLE1 AS X
SET VALUE1=
(SELECT APPLES FROM TABLE2 WHERE ID = X.VALUE2)
-
(SELECT ORANGES FROM TABLE2 WHERE ID = X.VALUE3)
WHERE X.ID=12;
答案 0 :(得分:1)
使用JOIN
代替相关子查询:
UPDATE TABLE1 AS x
JOIN TABLE2 AS y1 ON y1.id = x.value2
JOIN TABLE2 AS y2 ON y2.id = x.value3
SET value1 = y1.apples = y2.oranges
WHERE x.id = 12