欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

場(chǎng)景

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

方案

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

小批量數(shù)據(jù),由于數(shù)據(jù)量少,通過 復(fù)制數(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(), '手機(jī)', 2, 'category', 'phone', '2021');

...

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

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

這里,我通過 UUID + 自增來實(shí)現(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)了一張臨時(shí)自增表,即:(select @i:=1000) as t  這里定義的 1000 為從 1000 開始,每一條記錄,自增 1,為了避免與原 ID 出現(xiàn)重復(fù)現(xiàn)象,使用了 UUID 函數(shù)生成新記錄,并截取后重新進(jìn)行自增拼接,這樣,就完美的解決了使用 insert into select 在同一張表里進(jìn)行數(shù)據(jù)插入時(shí)的 主鍵沖突問題。

3、備份表常用 SQL

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

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


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

-- 只復(fù)制表,不包含數(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論