SQL SERVER-5-子查询|分页查询

1.子查询

--在一个查询中又包含另外一个查询,这种情况就叫做子查询

--在使用子查询的时候,子查询语句要使用括号括起来,可以不起别名也可以起别名
select * from (select tsname,tsage,tsgender from TblStudent) as t1


--使用in,根据查询出来的人员信息的ID来查询他们对应的分数
--在使用in的时候,子查询语句查询出来的只能是一列,不能是多列
select * from TblScore where tsid in
(select tsid from TblStudent where tsname in ('黄忠','关羽','小乔乔'))

--这个语句和上面的相同,只是查询条件不同
select tsid,tsgender,tsname,tsclassId from TblStudent
where tsclassId in
(
    select tclassId from TblClass where tclassname='高一一班' or  tclassname='高二二班'
)


--exists表示判断是否成立,成立返回true,不成立返回false
--下面的语句表示查询出所有的成立的学生信息,这些学生的班级ID必须在班级表中有数据,并且在班级表中查询出来一班和二班的并且
select * from TblStudent as ts where exists
(
    select * from TblClass as tc
    where tc.tclassId=ts.tsclassId and (tc.tclassname='高一一班' or tc.tclassname='高二二班')
)

2.分页查询
--1.通过top来实现,需要先按照指定的规则来排序

--假设每页5条数据

--第一页
select top 5 * from ZY_BRSYK order by syxh


--第n页的数据,每页5条
--1.先找已经看过的数据
--2.从整个数据中排除已经看过的数据
--3.然后在对未查看过的数据进行排序,取前5条。
select top 5 * from ZY_BRSYK where syxh not in
(select top ((n-1)*5) syxh from ZY_BRSYK order by syxh asc)
order by syxh asc

--n可以是任何数字
select top 5 * from ZY_BRSYK where syxh not in
(select top (8*5) syxh from ZY_BRSYK order by syxh asc)
order by syxh asc


--2.使用排序的方式取值
select * from (
select top 5 * from ZY_BRSYK where syxh in
(select top (n*5) syxh from ZY_BRSYK order by syxh asc)
order by syxh desc
) t order by t.syxh asc

--n取任意数字
select * from (
select top 5 * from ZY_BRSYK where syxh in
(select top (3*5) syxh from ZY_BRSYK order by syxh asc)
order by syxh desc
) t order by t.syxh asc

--3.使用row_number()来进行分页,row_number()是对查询出的结果集进行编号,并不影响表中已有的数据
--假设每页5条,要看第n页的数据
--(n-1)*5+1    到   n*5

select
    row_number() over(order by syxh asc) as pxxh ,
    *
from ZY_BRSYK

--每页7条,看第4页。
select * from
(
select
    row_number() over(order by syxh asc) as pxxh ,
    *
from ZY_BRSYK
) as Tbl where Tbl.pxxh between (4-1)*7+1 and 4*7

猜你喜欢

转载自blog.csdn.net/m0_37532448/article/details/82868025