首页 文章

如何根据另一个表中的值更新记录? [重复]

提问于
浏览
0

这个问题在这里已有答案:

我使用Firebird 3.0,我有3个表:

表1:tbl1_id(PK),f2_id(FK),tbl1_f1

tbl1_f2是table2的外键

表2:f2_id(PK),f3_id(FK)

f3_id是table3的外键

表3:f3_id(PK),tbl3_code

现在我需要设置Table1.tbl1_f1 = 1,其中Table3.tbl3_code ='value'所以我写了这个SQL:

update table1 set tbl1_f1 = 1 where (tbl1_f1 is null)
and table1.tbl1_id in (

select
    tbl1_id

from table1 
   inner join Table2 on (Table1.f2_id = Table2.f2_id)
   inner join Table3 on (Table2.f3_id = Table3.f3_id)

where (Table3.tbl3_code = 'value')

 )

我的更新SQL是正确的还是有更好的方法来编写它?

1 回答

  • 1
    execute block
    as
    declare id bigint;
    begin
    for select tbl1_id
    from table1 
       inner join Table2 on (Table1.f2_id = Table2.f2_id)
       inner join Table3 on (Table2.f3_id = Table3.f3_id)
    where (Table3.tbl3_code = 'value')
    into :id
    do update table1 set tbl1_f1 = 1 where (tbl1_f1 is null)
    and table1.tbl1_id =:id;
    
    end;
    

相关问题