亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

MySQL insert into select 主鍵沖突解決方案

 更新時間:2024年06月27日 10:35:45   作者:搬運Gong  
本文主要介紹了MySQL insert into select主鍵沖突解決方案,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

場景

項目中,一張表里的基礎(chǔ)數(shù)據(jù),ID 是以 varchar 類型存入的,由于每年都會存在變動,在不改變歷史數(shù)據(jù)的情況下,每年生產(chǎn)一份當年使用的數(shù)據(jù),如果當年基礎(chǔ)數(shù)據(jù)有變動,則改動當年的數(shù)據(jù),往年歷史數(shù)據(jù)不做變更,通過邏輯進行數(shù)據(jù)分隔。

方案

1、小批量數(shù)據(jù)

小批量數(shù)據(jù),由于數(shù)據(jù)量少,通過 復制數(shù)據(jù)庫中原數(shù)據(jù)生成 insert 腳本,使用 UUID 來處理了主鍵問題,如下:

INSERT INTO test_category (id, create_date, update_date, label, sort, type, value, year) VALUES (replace(uuid(),'-',''), now(), now(), '汽車', 1, 'category', 'automobile', '2021');

INSERT INTO test_category (id, create_date, update_date, label, sort, type, value, year) VALUES (replace(uuid(),'-',''), now(), now(), '手機', 2, 'category', 'phone', '2021');

...

因為數(shù)據(jù)量少,自己修改腳本也花不了多長時間,那么,如果數(shù)據(jù)量大,再這么寫就不行了,需要處理成百上千,甚至更多的時候,要怎么做呢?

2、大批量數(shù)據(jù)

這里,我通過 UUID + 自增來實現(xiàn),具體 SQL 如下:

INSERT INTO test_category (id, name, kind_id, sort, type, year)
select concat(left(replace(uuid(),'-',''),28),(@i:=@i+1)) as id, name, kind_id, sort, type,'2022' as year
from exhibits_dict_new edn
left join (select @i:=1000) as t on 1 = 1
where year = '2021';

需要注意,這里關(guān)聯(lián)了一張臨時自增表,即:(select @i:=1000) as t  這里定義的 1000 為從 1000 開始,每一條記錄,自增 1,為了避免與原 ID 出現(xiàn)重復現(xiàn)象,使用了 UUID 函數(shù)生成新記錄,并截取后重新進行自增拼接,這樣,就完美的解決了使用 insert into select 在同一張表里進行數(shù)據(jù)插入時的 主鍵沖突問題。

3、備份表常用 SQL

-- 創(chuàng)建一張表結(jié)構(gòu)、索引信息一模一樣的  空表
create table test_category_bak like test_category;

-- 往新備份的表中,插入需要備份的數(shù)據(jù)  全量備份,也可以在后面加上 where 條件進行條件備份
insert into test_category_bak select * from test_category;


-- 復制表,包含表中的數(shù)據(jù)
create table table_name2 as select * from table_name1;

-- 只復制表,不包含數(shù)據(jù)內(nèi)容
create table table_name2 as select * from table_name1 where 1=2;

到此這篇關(guān)于MySQL insert into select 主鍵沖突解決方案的文章就介紹到這了,更多相關(guān)MySQL insert into select 主鍵沖突內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評論