SQL分页笔记
据说这样分页效率比较高。
video-视频表(主键为videoid)
videotype-视频类型(主要是videoid,type)
要求1:分页查询出视频标题存在'精华'的视频
当pageIndex为1时:
select top pageSize video.* from video
where title like '%精华%'
当pageIndex大于1时:
select top pageSize video.* from video
left join
(select top (startIndex - 1) videoid from video
where title like '%精华%'
) tempTable on video.videoid =tempTable.videoid
where tempTable.videoid is null
and title like '%精华%'
要求2:分页查询出视频类型为'编辑推介'的视频
当pageIndex为1时:
select top pageSize video.* from video
inner join videotype on video.videoid=videotype.videoid
where videotype.type= '编辑推介'
当pageIndex大于1时:
select top pageSize video.* from video
inner join videotype on video.videoid=videotype.videoid
left join
(select top (startIndex - 1) video.videoId from video
inner join videotype on video.videoid=videotype.videoid
where videotype.type = '编辑推介'
) tempTable on video.videoId=tempTable.videoId
where tempTable.videoId is null
and videotype.type = '编辑推介'
说明:
如果没有写入order by排序语句,那么结果集的默认排序规律是以所选择数据表中索引排序.
startIndex的值是某页的第一条序号,如pageSize是2,pageIndex是3,那么startIndex为5.
tempTable中是某页之前的所有结果,用于left join原表,加上tempTable.videoId is null后会去掉本页之前的结果,在剩下的结果集中选择top pageSize即是所需结果。