Mysql關聯刪除CSV中的相關數據

問題描述:提供一個csv文件,記錄的是一些不同數據庫的不同表中的共同字段account_id數據,需要在A庫的account表中做關聯刪除

 

解決思路:csv文件中儲存的都是account_id,六位純數字id。可以建立一張臨時表,將csv數據導入臨時表中,最後做關聯刪除。

1.備份原表
CREATE table A.account_0220 as select * from A.account;
alter table A.account_0220 comment = 'This is a backup table. Please drop it after 20230320';

2.導入數據到臨時表
創建臨時表
create table test.transit_tmp(account_id int);

導入數據到臨時表
load data local infile '/tmp/0220/202302201526.csv' 
into table test.transit_tmp
fields terminated by ',' optionally enclosed by '"' escaped by '"'
lines terminated by '\r\n';


查詢臨時表數據量
select count(*) from transit_tmp;
+----------+
| count(*) |
+----------+
|    10369 |
+----------+
1 row in set (0.003 sec)

3.查詢數據是否匹配
查詢account表中與tmp關聯數據行數,查詢到匹配數據與實際csv數據相差一行
MariaDB [(none)]> select count(*) from A.account  where account_id in (select * from test.transit_tmp);
+----------+
| count(*) |
+----------+
|    10368 |
+----------+
1 row in set (42.539 sec)
MariaDB [test]> select * from transit_tmp order by account_id asc limit 1;
+------------+
| account_id |
+------------+
|          0 |
+------------+
1 row in set (0.003 sec)

MariaDB [test]> select * from transit_tmp order by account_id asc limit 2;
+------------+
| account_id |
+------------+
|          0 |
|     261607 |
+------------+
2 rows in set (0.003 sec)
查詢到數據不匹配,csv文件中有一行是字段名,load data把account_id這一行當成0插入到了臨時表中

 

刪除test.transit_tmp表中數據爲0的一行

delete from test.transit_tmp where account_id='0';

 

4.清理目標表相關數據

set autocommit=0

delete from A.account where account_id in (select * from test.transit_tmp); 

commit;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章