SQL聯表進行更新與刪除(使用聯表條件)


聯表刪除

語法:

  delete t1.* from t1, t2 where condition

案例:

  由於程序bug,導致對賬單生成了重復的對賬單條目數據,現在需要刪除掉重復數據。

  如何判斷重復:對賬條目表的對賬單號相同、來源info_no相同的多條記錄視為一條有效記錄,存在重復。

 

  sql:

  

DELETE t1.*
FROM
    verify_account_item t1,
    (
        SELECT
            verify_account_no,
            info_no,
            max(item_no) AS item_no
        FROM
            verify_account_item
        GROUP BY
            verify_account_no,
            info_no
        HAVING
            count(*) > 1
    ) t2
WHERE
    t1.item_no != t2.item_no
AND t1.verify_account_no = t2.verify_account_no

 

 

聯表更新:

語法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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM