29-3 union的使用

联合结果集union (集合运算符)

-------------------------使用union联合结果集----------------
select tsname,tsgender,tsage from TblStudent
union all
select fname,fgender,fage from MyStudent
--------------------------------------------

--使用union和union all都能进行联合,区别在于:使用union联合去除重复、重新排列数据,而union all不会去除重复也不会重新排列。
select select tsname,tsgender,tsage from TblStudent
union 
select fname,fgender,fage from MyStudent
--大多数情况下,联合的时候不需要去除重复,同时要保持数据的顺序,所以一般建议使用union all

--从MyOrder表中统计每种商品的销售总价,并且在底部做汇总

select 
    商品名称,
    销售总价=sum(销售价格*销售数量)
from MyOrder
group by 商品名称
union all
select 
     '总销售价格',
     sum(销售价格*销售数量)
order by 销售总价 asc

--要查询成绩表中的:最高分,最低分,平均分

select
     max(tmath) as 最高分,
     min(tmath) as 最低分,
     avg(tmath) as 平均分
from MyOrder


select 名称='最高分',分数=max(tmath) from TblScore
union all
select 名称='最低分',分数=min(tmath) from TblScore
union all
select 名称='平均分',分数=avg(tmath) from TblScore
-------------------------使用union向表中插入多条数据-----------------------------
select * from TblStudent
insert into TblStudent
select '赵玉西','','北京市海定区','1388888888',18,'1990-9-9','123456789123456789',3
union all
select '赵玉西1','','北京市海定区1','1388888889',18,'1990-9-6','123456789123456788',1
union all
select '赵玉西2','','北京市海定区2','1388888885',18,'1990-9-3','123456789123456787',5
union all
select '赵玉西3','','北京市海定区3','1388888882',18,'1990-9-2','123456789123456786',4
union all
select '赵玉西4','','北京市海定区4','1388888881',18,'1990-9-1','123456789123456785',6


---在使用union进行插入数据的时候,也要注意union会去除重复的
select * from TblStudent
insert into TblStudent
select '赵玉西','','北京市海定区','1388888888',18,'1990-9-9','123456789123456789',3
union
select '赵玉西','','北京市海定区','1388888888',18,'1990-9-9','123456789123456789',3
union
select '赵玉西','','北京市海定区','1388888888',18,'1990-9-9','123456789123456789',3
union
select '赵玉西','','北京市海定区','1388888888',18,'1990-9-9','123456789123456789',3

最好还是使用union all。

原文地址:https://www.cnblogs.com/Strugglinggirl/p/7205118.html