SQL联表更新

联表更新:

语法1(表连接写法):

  update t1, t2  set t1.col1 = t2.col2 where condition

案例:

 订单表新增了父单号,原来的对账信息里面也新增了父单号,但是数据没有清洗进去,因此这里进行数据清洗。

sql:

update
    app_order_info t1
INNER JOIN verify_account_pool_info t2 ON t1.order_num = t2.sale_order_no
set t2.f_sale_order_no = t1.parent_order_id
where t1.parent_order_id is not null;

语法2(子查询写法):

  update t1 set t1.col1 = (select col2 from t2 where col3 = t1.col3) 

案例:

  客商档案表新增了两个字段,冗余客商信息方便查询,这里需要进行数据清洗,写入初始数据

sql:

update bd_cumandoc set
 `resp_user_name` = (select PSNNAME from bd_user where PK_PSNDOC = bd_cumandoc.pk_resppsn1),
`resp_dept_name` = (select DEPTNAME from bd_dept where PK_DEPTDOC = bd_cumandoc.pk_respdept1) 
where     pk_respdept1 IS NOT NULL
AND pk_resppsn1 IS NOT NULL;

注意,单表和表关联是同一张表,产生套娃情况修改和删除可能会报错,错误原因是不能在where条件依据进行更改的表作为条件。这个时候,可以使用临时表作为介质辅助删除。

例子sql:

CREATE TEMPORARY TABLE temp_Item_tab(
    item_id varchar(50) not null
);
insert into temp_Item_tab (item_id)
select sale_agreement_item_id from app_sale_agreement_item where sale_agreement_item_id not in (
    select min(sale_agreement_item_id) as itemId from app_sale_agreement_item 
    group by sale_agreement_id, product_id, customer_id
);

delete t1.*
FROM
    app_sale_agreement_item t1,
    temp_Item_tab t2
WHERE
    t1.sale_agreement_item_id = t2.item_id;

参考:

SQL联表进行更新与删除(使用联表条件) - guodaxia - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值