我目前有以下三个表格:
表1
book_id margin
-------------------
b1 10
b2 20
b3 30
表2
t2_id book_id author_id
-----------------------------
1 b1 100
2 b2 200
3 b3 300
表3
author_id revenue
----------------------
100 0
200 0
300 0
我试图用表1的对应书作者(表3)的保证金的50%更新表3的收入。结果应将表3更新为:
author_id revenue
----------------------
100 10
200 20
300 30
如果它们可以通过公用键直接链接到另一个表中,则可以更新另一个表中的值,而我不得不在中间引用另一个表以获取答案:(
我尝试过:
UPDATE table3 t3 SET revenue =
(SELECT t1.margin FROM table1 t1 WHERE
(SELECT t1.book_id FROM table1 t1 JOIN table2 t2 ON t1.book_id = t2.book_id) =
(SELECT author_id FROM table3 t3 JOIN table2 t2 ON t3.authoer_id = t2.author_id));
谢谢
答案 0 :(得分:2)
使用update with join
update
(
SELECT table3.revenue as OLD, table1.margin as NEW
FROM table1 INNER JOIN table2 on table1.book_id=table2.book_id
inner join table3 on table2.author_id=table3.author_id
)t set t.old=t.new
答案 1 :(得分:1)
对子查询使用合并更新
MERGE INTO table3 t3
using
(select t1.margin,t2.author_id
from tabl1 t1 join table2 t2 on t1.book_id=t2.book_id
) a ON (t3.author_id = a.author_id)
when matchced then
update SET t3.revenue = a.margin
答案 2 :(得分:1)
您也可以通过使用update
方法来使用with..as
:
update table3 t3
set t3.revenue =
(with t as (
select *
from table1 t1
join table2 t2 on t2.book_id = t1.book_id
)
select t.margin from t where t.author_id = t3.author_id);