当产品出现在 temp table 中时,根据 temp 中的所有订单类型的记录更新语句 main table

update statement main table based on records in temp all types of an order when a product present in temp table

如果临时 table 中存在订单产品类型的单个项目,我必须为每个 order_id 更新产品类型的所有项目的状态。以下是 3 tables

产品table

温度table

主要table

我正在主 table 中使用以下语句更新状态 product_type 的所有项目 order_id 如果即使是 product_type 的单个项目temp table

中存在订单
update main_table t 
set status='inactive' 
from (  select i.order_id,
               pt.type 
        from temp_table i 
        inner join product_table pt  on i.product_id=pt.product_id 
        where i.key is not null ) as a1 
                
inner join (  select mt.order_id,
                     mt.key,pt1.type 
              from main_table mt 
              inner join product_table pt1  on mt.product_id=pt1.product_id) a2 
   on a1.order_id=a2.order_id 
   and a1.type=a2.type 
     
where t.key=a2.key

预期输出为

main table 有 1000 万条记录,temp table 可能有 2K 条记录。我认为上面的查询很复杂,因为它有 2 个子查询和连接。

有没有一种方法可以重写查询以改进查询执行?

您的查询有点太复杂,无法进一步简化,因为需要多次加入产品才能获得相同 product_type 的所有 product_id。但是,我们可以将您的 a2 查询重新处理到主 UPDATE 语句中,从而消除至少 1 个针对 main.

的连接
update  main mt
set prodstatus = 'inactive'
from product p 
inner join (select i.order_id,
                   pt.prodtype 
            from temp i 
            inner join product pt on i.product_id=pt.product_id 
            where i.pk is not null) as tempProds
  on p.prodtype = tempProds.prodType
where mt.product_id = p.product_id  
  and mt.order_id = tempProds.order_id

This fiddle 向您展示了如果您 运行 我们的 UPDATE 语句分别使用 EXPLAIN 选项的执行优势。