取A表的某些列的資料插入到B表中(複製)

2021-09-24 18:19:55 字數 1696 閱讀 8777

第一步:建立乙個臨時表tmp

create table 'tmp'(

'id' varvhar(36) not null,

'memberid' varvhar(36) dffault null,

'shopid' varvhar(255) dffault null,

primary key ('id')

) engine=innodb default charset=uft-8;

可只取其關鍵字段(變數),其餘列可寫死的,就不用加入到新錶的列中,臨時表只儲存變數即可,相對會快。

select * from tmp

select count(1) from tmp

驗證是否建立了臨時表。

第二步:將a表的資料匯入到臨時表'tmp'中,這裡只匯入其變數即可,據臨時表的列而定

insert into 'tmp' ('id','memberid','shopid') select id,memberid,shpid from table_a

insert into 'tmp' ('id','memberid','shopid') select id,memberid,shpid from table_a where id like '131%' limit 1000; --此處同樣可以加入查詢條件

第三步:查詢下資料是否匯入到臨時表

select * from tmp

select count(1) from tmp

第四步:將臨時表的資料匯入到b表(複製到a表)中,使用拼接

-- 將臨時表的資料插入到b表

insert into 'o2o'.'table_b'(

'id',

'addtime',

'memberid',

'remark',

'shopid',

'tag'

)select

id,'2018-11-13 03:11:06', --也可以使用函式now()等等獲取當前時間or日期

memberid,

null,

shopid,

null

from tmp where id like '131%' limit 1000

-- 將臨時表的資料複製到a表

insert into 'o2o'.'table_a'(

'id',

'addtime',

'memberid',

'remark',

'shopid',

'tag'

)select --concat('1',id), 亦可以寫成這樣

concat(id,'1'), --意思是在id的後面拼接1個『1』,保證資料的唯一,在你此列長度夠的情況下可用

'2018-11-13 03:11:06', --也可以使用函式now()等等獲取當前時間or日期

concat(memberid,'1'),

null,

concat(shopid,'1'),

null

from tmp where id like '131%' limit 1000

插入資料a表到b表

insert into p web p p.tid,p.title,p.fileurl,p.columnid,p.columnname select l.tid,l.linkname,l.linkurl,3033 as columnid from p link l where l.columnid ...

mysql把A表資料插入到B表資料的幾種方法

web開發中,我們經常需要將乙個表的資料插入到另外乙個表,有時還需要指定匯入字段,設定只需要匯入目標表中不存在的記錄,雖然這些都可以在程式中拆分成簡單sql來實現,但是用乙個sql的話,會節省大量 下面我以mysql資料庫為例分情況一一說明 1.如果2張表的字段一致,並且希望插入全部資料,可以用這種...

查詢A表資料插入到B表中 sql

通常使用的插入sql語句大部分是 insert into a a,b,c values 1,2,3 4,5,6 1.同乙個資料庫,a表存在時 在一些特殊的情況下 也可以使用 insert into a a,b,c select a,b,c from b 但是需要注意的是 在這種情況中的 values...