Как обновить записи на основе значений из другой таблицы?

Я использую 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 ответ

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;
Другие вопросы по тегам