-----------------------独立子查询,相关子查询------------------- --一个查询的结果集作为另一个查询的查询源,这个查询的结果集需要起一个别名 --独立子查询,内部的子查询可以独立运行,没有涉及到外部查询的任何数据 select * from (select tsname, tsgender, tsbirthday from TblStudent) as t ------------------ select * from TblClass select * from TblStudent --查出特长班跟理科班的学生 --select * from TblStudent -- where tSClassId in --(select tClassId from TblClass where tClassDesc='理科班' or tClassDesc='特长班') -----------相关子查询 --select * from TblStudent as stu --where exists --( -- select * from TblClass as tclass -- where (tclass.tClassDesc='特长班' or tclass.tClassDesc='理科班' )and tclass.tClassId=stu.tSClassId --) --------------------- --查询所有高一一班和高一二班的所有学生 select * from TblStudent where tSClassId in(select tClassId from TblClass where tClassName='高一一班' or tClassName='高一二班') --查询刘关张的成绩 select * from TblScore select * from TblStudent select * from TblScore where tSId in(select tSId from TblStudent where tSName in('关羽','张飞','刘备')) -------------------------------------分页---------------------------------------- --查询第三页,思路:首先查询出我们前两页的记录,然后查询出不在这前两页的记录里面的前几条(一页的条数) select * from Customers select top 5 * from Customers where CustomerID not in (select top 10 CustomerID from Customers) select * from Customers select top 5 * from Customers where CustomerID not in (select top 10 CustomerID from Customers order by CustomerID) order by CustomerID --使用row_number()方式,每页n条,要看第i页 --1.为每条记录编号,2.根据用户要查询的记录,从指定的编号区间中查询 select * from ( select *,rn=ROW_NUMBER()over(order by customerId asc) from Customers--编号 ) as t where t.Rn between(5*3)+1 and(5*4) -----------------------------连接查询--------------------------------- --合并两个表或多个表的列,union是连接行 select * from TblStudent,TblClass ---两个表内连接的时候,会将两个表的记录总个数相乘(笛卡尔积) --内连接,只找那些有匹配的记录 --案例1.查询所有学生的姓名、年龄、及所在的班级 select ts.tSname, ts.tSAge, tc.tclassName from TblStudent as ts inner join TblClass as tc on tc.tClassId=ts.tSClassId --案例2:查询年龄超过20岁的学生的姓名、年龄及所在班级 select ts.tSname, ts.tSage, tc.tclassName from TblStudent as ts inner join TblClass as tc on tc.tClassId=ts.tSClassId where ts.tSage>20 --案例3:查询学生姓名、年龄、班级及成绩 select * from TblScore select ts.tSName, ts.tSAge, tc.tClassName, s.tMath, s.tEnglish from TblStudent as ts inner join TblClass as tc on tc.tClassId=ts.tSClassId inner join TblScore as s on s.tSID=ts.tSId -- 外连接 --外连接,显示一个表中的所有记录 --如果没有则显示null --案例4:查询所有学生(参加及未参加考试的都算)及成绩 select ts.*, s.tEnglish, s.tMath from TblStudent as ts left join TblScore as s on s.tSId=ts.tSId --案例5:请查询出所有没有参加考试(在成绩表中不存在的学生)的学生的姓名。 select * from TblStudent as ts left join TblScore as s on s.tSId=ts.tSId where s.tScoreId is null --and连接的时候就执行了 --where 是基于结果集执行的 --注意:在使用外连接的时候,如果要对连接 --查询后的结果进行筛选 --必须使用where --不能直接在on条件后加and
自连接案例
select t1.EmployeeID, t1.FirstName, t1.ReportsTo, t2.FirstName from Employees as t1, Employees as t2 where t1.ReportsTo=t2.EmployeeID select t1.AreaPId, t1.AreaName, t2.AreaName from TblArea as t1, TblArea as t2 where t1.AreaPId=t2.AreaId