本節(jié)介紹數(shù)據(jù)的插入揖盘,復(fù)制數(shù)據(jù)到另一張表的Sql語法眉厨,主要語法有:insert into,insert into select兽狭,select into from等用法憾股,下面將一一為大家詳細(xì)說明:
以下面兩張表進(jìn)行sql腳本說明
1鹿蜀、insert into? ?--數(shù)據(jù)插入
insert into有兩種語法,分別如下:
語法1:INSERT INTO?table_name?VALUES (value1,value2,value3,...);? ?--這種形式無需指定要插入數(shù)據(jù)的列名服球,只需提供被插入的值即可:
語法2:INSERT INTO?table_name?(column1,column2,column3,...) VALUES (value1,value2,value3,...);? ?--這種形式需指定要插入數(shù)據(jù)的列名茴恰,插入的值需要和列名一一對應(yīng):
eg:insert into customer values('1006','14006','王欣欣','27','深圳市');? --向表customer插入一條數(shù)據(jù)
eg:insert into customer values('1007','14007','孟一凡','27','');? ? ? ? ? ? ?--向表customer插入一條數(shù)據(jù),最后一個值不填表示對應(yīng)的值為空斩熊,非必填項(xiàng)可以不用插入值
eg:insert into customer (cus_id,cus_no,cus_name,cus_age,cus_adds) values('1008','14008','孔凡','26','廣州市');? ? ? --向表customer插入一條數(shù)據(jù)往枣,插入的值與列名一一對應(yīng)
2、insert into select? ? --復(fù)制數(shù)據(jù)
詳解:insert into select? ? --表示從一個表復(fù)制數(shù)據(jù)座享,然后把數(shù)據(jù)插入到一個已存在的表中婉商。目標(biāo)表中任何已存在的行都不會受影響。
語法1:INSERT INTO?table_name2?SELECT? * FROM?table_name1;? --表示將表table_name1中復(fù)制所有列的數(shù)據(jù)插入到已存在的表table_name2中渣叛。被插入數(shù)據(jù)的表為table_name2丈秩,切記不要記混了。
eg:insert into customer select * from asett? --將表asett中所有列的數(shù)據(jù)插入到表customer中
語法2:INSERT INTO?table_name2?(column_name(s))?SELECT?column_name(s)?FROM?table_name1;? --指定需要復(fù)制的列淳衙,只復(fù)制制定的列插入到另一個已存在的表table_name2中:
eg:insert into customer (cus_id,cus_no) select ast_id,ast_no from asett? --將表asett中列ast_id和ast_no的數(shù)據(jù)插入到表customer對應(yīng)的cus_id蘑秽,cus_no列中
3、select? into from? --表復(fù)制數(shù)據(jù)
詳解:從一個表復(fù)制數(shù)據(jù)箫攀,然后把數(shù)據(jù)插入到另一個新表中肠牲。
語法1:SELECT * INTO?newtable?[IN?externaldb] FROM?table1;?? ? ? ? ? ? ? ? ? ? ? ? ? ? ?--復(fù)制所有的列插入到新表中:
eg:select * into?customer from?asett? ??--將asett表中數(shù)據(jù)插入到customer中,被插入的表customer不存在
eg:select * into?customer from?asett where ast_id = '1008'? ?--只復(fù)制表asett中ast_id=1008的數(shù)據(jù)插入到customer中靴跛,被插入的表customer不存在
語法2:SELECT?column_name(s)?INTO?newtable?[IN?externaldb] FROM?table1;? ?--只復(fù)制指定的列插入到新表中:
eg:select ast_id,ast_no into?customer?from?asett? --將asett表中列ast_id,ast_no數(shù)據(jù)插入到customer中缀雳,被插入的表customer不存在
4、insert into select 與select? into from 區(qū)別
區(qū)別1:insert into customer select * from asett where ast_id='1009' --插入一行,要求表customer?必須存在
區(qū)別2:select * into customer? from asett? where ast_id='1009' --也是插入一行,要求表customer? 不存在
區(qū)別3:select into from?:將查詢出來的數(shù)據(jù)復(fù)制到一張新表中保存梢睛,表結(jié)構(gòu)與查詢結(jié)構(gòu)一致肥印。
區(qū)別4:insert into select?:為已經(jīng)存在的表批量添加新數(shù)據(jù)。