SQL 教程,SQL 在线

2583SQL INSERT INTO SELECT

稍微整理一下 select into from 和 insert into select 的理解层面的区别

select into from :将查询出来的数据整理到一张新表中保存,表结构与查询结构一致。

select *(查询出来的结果) into newtable(新的表名)form where (后续条件)

即,查询出来结果--->复制一张同结构的空表--->将数据拷贝进去。

insert into select :为已经存在的表批量添加新数据。

insert into  (准备好的表) select *(或者取用自己想要的结构)frome 表名 where 各种条件

即,指定一张想要插入数据的表格--->对数据进行加工筛选--->填入一张准备好的表格。

嗯,可能理解的比较粗浅,希望有知识经验的大佬及时订正。

2582SQL INSERT INTO SELECT

select into from 和 insert into select 都是用来复制表

两者的主要区别为: select into from 要求目标表不存在,因为在插入时会自动创建;insert into select from 要求目标表存在。

1. 复制表结构及其数据:

create table table_name_new as select * from table_name_old

2. 只复制表结构:

create table table_name_new as select * from table_name_old where 1=2;

或者:

create table table_name_new like table_name_old

3. 只复制表数据:

如果两个表结构一样:

insert into table_name_new select * from table_name_old

如果两个表结构不一样:

insert into table_name_new(column1,column2...) select column1,column2... from table_name_old

2581SQL UNION

ORDER BY 除了可以对指定的字段进行排序,还可以使用函数进行排序:

order by abs(a);

ORDER BY 只能当前 SQL 查询结果进行排序,如要对 union all 出来的结果进行排序,需要先做集合。

select aa.* from 
(select country,name from websites where country = 'CN'
union all select country,app_name from apps where country='CN' ) aa
order by aa.name;

2580SQL UNION

使用UNION命令时需要注意,只能在最后使用一个ORDER BY命令,是将两个查询结果合在一起之后,再进行排序!绝对不能写两个ORDER BY命令。

另外,在使用ORDER BY排序时,注意两个结果的别名保持一致,使用别名排序很方便。当然也可以使用列数。

2579SQL UNION

select country from websites union select country from apps;
--连接两个表的查询结果集,重复的不显示
select country from websites union all select country from apps order by country;
--连接俩个个表的查询结果集,显示重复
select country,name from websites where country = 'CN' union all 
select country,app_name from apps where country='CN' order by name; 
--通过where条件查询的结果,连接连个表的结果集,并根据名字排序。