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