select?into?from和insert?into?select的區(qū)別舉例詳解
一、區(qū)別解釋
1、select into from :將查詢出來的數(shù)據(jù)整理到一張新表中保存,表結(jié)構(gòu)與查詢結(jié)構(gòu)一致。
select *(查詢出來的結(jié)果) into newtable(新的表名)from where (后續(xù)條件)
即,查詢出來結(jié)果—>復(fù)制一張同結(jié)構(gòu)的空表—>將數(shù)據(jù)拷貝進去。
2、insert into select :為已經(jīng)存在的表批量添加新數(shù)據(jù)。
insert into (準(zhǔn)備好的表) select *(或者取用自己想要的結(jié)構(gòu))from 表名 where 各種條件
即,指定一張想要插入數(shù)據(jù)的表格—>對數(shù)據(jù)進行加工篩選—>填入一張準(zhǔn)備好的表格。
二、舉例詳解
select into from 和 insert into select 都是用來復(fù)制表
兩者的主要區(qū)別為: select into from 要求目標(biāo)表不存在,因為在插入時會自動創(chuàng)建;insert into select from 要求目標(biāo)表存在。
- 復(fù)制表結(jié)構(gòu)及其數(shù)據(jù):
create table table_name_new as select * from table_name_old
- 只復(fù)制表結(jié)構(gòu):
create table table_name_new as select * from table_name_old where 1=2;
或者:
create table table_name_new like table_name_old
- 只復(fù)制表數(shù)據(jù):
如果兩個表結(jié)構(gòu)一樣:
insert into table_name_new select * from table_name_old
如果兩個表結(jié)構(gòu)不一樣:
insert into table_name_new(column1,column2...) select column1,column2... from table_name_old
注意事項:
SELECT INTO 只能用于創(chuàng)建新表,而 INSERT INTO SELECT 可以用于向已存在的表中插入數(shù)據(jù)。
SELECT INTO 會自動創(chuàng)建新表,如果新表已存在,會報錯。而 INSERT INTO SELECT 不會創(chuàng)建表,只會向現(xiàn)有表中添加數(shù)據(jù)。
在使用 INSERT INTO SELECT 時,可以選擇性地插入數(shù)據(jù),通過 WHERE 子句過濾數(shù)據(jù),或者使用 ORDER BY 對數(shù)據(jù)進行排序。
在使用 SELECT INTO 時,如果選擇的列與新表中的列不完全匹配,SQL Server 會自動創(chuàng)建列,但可能會丟失數(shù)據(jù)類型和約束。
總結(jié)
到此這篇關(guān)于select into from和insert into select的區(qū)別的文章就介紹到這了,更多相關(guān)select into from和insert into select區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MySQL explain根據(jù)查詢計劃去優(yōu)化SQL語句
MySQL是一種常見的關(guān)系型數(shù)據(jù)庫管理系統(tǒng),常被用于各種應(yīng)用程序中存儲數(shù)據(jù),當(dāng)涉及到大量的數(shù)據(jù)時,就需要MySQL的explain功能來幫助優(yōu)化,本文將詳細介紹MySQL的explain功能,感興趣的朋友可以參考閱讀2023-04-04mysql設(shè)置更改root密碼、mysql服務(wù)器的連接、mysql常用命令的圖解
這篇文章主要介紹了mysql設(shè)置更改root密碼、mysql服務(wù)器的連接、mysql常用命令,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06