CSharp基础起步第十八期---SqlServer 基础06(联合查询)
1.联合结果集union(集合运算符)? 集合运算符是对两个集合操作的,两个集合必须具有相同的列数,列具有相同的数据类型(至少能隐式转换的),最终输出的集合的列名由第一个集合的列名来确定。(可以用来连接多个结果) 联合(union)与连接(join)不一样 简单的结果集联合(老师、学生): select tName,tSex from teacher union select sName,sSex from student 基本的原则:每个结果集必须有相同的列数;每个结果集的列必须类型相容。? select tName,tSex,-1 from teacher union select sName,sSex,sClassId from student 联合:将多个结果集合并成一个结果集。union(去除重复,相当于默认应用了distinct)、union all(保留所有结果,不去除重复) 2.Union all ? ? ? ? ? select tName,tSex from teacher union ? ? ? ? ? select sName,sSex from student UNION合并两个查询结果集,并且将其中完全重复的数据行合并为一条 select tName,tSex from teacher union all select sName,sSex from student Union因为要进行重复值扫描,所以效率低,因此如果不是确定要合并重复行,那么就用UNION ALL
3.案例1 要求在一个表格中查询出学生的英语最高成绩、最低成绩、平均成绩 查询结果为3行: select 'english最高成绩',max(english) from score? union all select 'english最低成绩',min(english) from score? union all select 'english平均',avg(english) from score 查询结果为1行: Select max(english),min(english),avg(english) from score; *一次插入多条数据 --把现有表的数据插入到新表(表不能存在),为表建备份。 ----select * into newStudent from student(newStudent表在select查询的同时自动建立。) --把现有表的数据复制到一个已存在的表 通过这种方式复制,只能复制表中的数据,以及列的名字和数据类型。对于约束,不会复制过来。 Select * into newTbl from oldTbl where 1<>1,这样做可以只复制表结构,但效率并不高。建议:select top 0 * into newTbl from oldTbl =========如果表已经存在了=============== ----insert into backupStudent select * from students(backupStudent表必须提前建好) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |