面试题目--SQL 查100条数据中的30-40条

news/2024/7/5 7:50:28

面试题目--SQL 查100条数据中的30-40

分页 sql 查询在编程的应用很多,主要有 存储过程分页和 sql分页两种,我比较喜欢用 sql分页,主要是很方便。为了提高 查询效率,应在排序字段上加索引。
sql分页 查询的原理很简单,比如你要查100条 数据中的 30- 40条,你先 查询出前 40条,再把这 30条倒序,再查出这倒序后的前十条,最后把这十条倒序就是你想要的结果。
        下面把 sql分页 查询的原理用 sql语句表现一下:

 

        -- 分页 升序(搜出的结果再倒序)
        SELECT TOP 10 * FROM (SELECT TOP 40 * from A01 ORDER BY A00 ASC) AS T ORDER BY A00 DESC

         -- 分页 升序
        SELECT * FROM (SELECT TOP 10 * FROM (SELECT TOP 40 * from A01 ORDER BY A00 ASC) AS T ORDER BY A00 DESC) AS T1 ORDER BY A00 ASC

         -- 分页 降序(搜出的结果再倒序)
         SELECT TOP 10 * FROM (SELECT TOP 40 * from A01 ORDER BY A00 DESC) AS T ORDER BY A00 ASC

         -- 分页 降序
         SELECT * FROM (SELECT TOP 10 * FROM (SELECT TOP 40 * from A01 ORDER BY A00 DESC) AS T ORDER BY A00 ASC) AS T1 ORDER BY A00 DESC

         为了应用的方便我把生成sql分页查询语句的写成了类SplitHelp

        应用如下:
       
       

/** <summary>
      /// 分页查询例子
      /// </summary>
      /// <param name="currentPage">当前页</param>
      /// <param name="pagesize">每页大小</param>
      /// <param name="count">数据总条数</param>
      /// <param name="cn">数据库连接</param>
      /// <returns>查询IDbCommand</returns>
      public IDbCommand Search(int currentPage, int pagesize, out int count, IDbConnection cn)
      {
         //得到IDbCommand
         IDbCommand cmd = cn.CreateCommand();
         cmd.CommandType = CommandType.Text;
        
         cmd.CommandText = "select count(tableTestID) from tableTest";
         if (cn.State != ConnectionState.Open)
            cn.Open();
         //得到数据总数
         count = (int)cmd.ExecuteScalar();

         //搜索的前n条
         int topAll = SplitPage.GetTopNum(currentPage, pagesize, count);

         //排序字段类
         AscDescClass ascDesc = new AscDescClass("tableTestID", AscDescEnum.desc);
         //ascDesc.Add("tableTestID1", AscDescEnum.desc);

         //此sql语名必须有排序,写出要查询前topAll条记录的sql
         string sql = String.Format(@"select top {0} * from tableTest order by {1}", topAll, ascDesc.GetAscDesString());
 
         //最终sql
         cmd.CommandText = SplitPage.GetFinalSql(sql, ascDesc, pagesize, count, topAll, currentPage);

         return cmd;
      }
当然,要想真正提高查询效率,最好还是用存储过程,这里写了两个例子,一个真对sql2000,一个真对sql2005

sql2000
create  proc usp_UserGoldHistoryByDateRange
    (
    @StartDate        varchar(10),
    @EndDate        varchar(10),
    @PageSize        int,
    @PageIndex        int,
    @RowCount        int out
    )
as
declare @StartRow    int
declare @EndRow    int
-- 计算当前页开始
set @StartRow = (@PageIndex - 1) * @PageSize + 1
-- 计算当前页结束
set @EndRow = @StartRow + @PageSize - 1

-- 建一张内存表用于存储检索结果
declare @temp table
    (
    AutoID     [int] IDENTITY (1, 1) NOT NULL,
    RowID    [int]
    )
-- 执行检索
insert into @temp(RowID)
select RowID from UserGoldHistory
where left(DateTimeTag,10) between @StartDate and @EndDate

set @RowCount = @@ROWCOUNT

select * from UserGoldHistory where RowID in (
select RowID from @temp where AutoID between @StartRow and @EndRow)

sql2005
create proc proc_Split
  -- 设置每页的
  @page_size int,
  -- 设置当前页
  @page_current int,
  -- 总记录数
  @rows_count int out
as

select @rows_count=count(UserName) from ForumUser

DECLARE @start_row_num int
DECLARE @end_row_num int
-- 设置开始
SET @start_row_num = (@page_current - 1) * @page_size + 1
-- 设置结束
SET @end_row_num = @start_row_num + @page_size - 1;

WITH temptesttable AS
(
  SELECT ROW_NUMBER() OVER(ORDER BY UserName) AS row_number, *
  FROM ForumUser
)
SELECT * from temptesttable
WHERE row_number BETWEEN @start_row_num AND @end_row_num

posted on 2006-12-09 19:22 来问(zljGood@hotmail.com) 阅读(517) 评论(4)  编辑 收藏 引用 网摘 所属分类: SQL技术

 
评论
# re: 分页查询的一个帮助类 2006-12-10 11:03 THIN
SQL语句何必要用临时表呢,要是要第100页呢,不是要先把几千条数据查出来?
查询查出ID就行了吧  回复  更多评论   

# re: 分页查询的一个帮助类 2006-12-10 13:19 S.Sams
数据一多,性能方面还是得考虑  回复  更多评论   

# re: 分页查询的一个帮助类 2006-12-10 16:35 来问(zljGood@hotmail.com)
@THIN

当然,要想真正提高查询效率,最好还是用存储过程,这里写了两个例子
多谢

sql2000
create proc usp_UserGoldHistoryByDateRange
(
@StartDate varchar(10),
@EndDate varchar(10),
@PageSize int,
@PageIndex int,
@RowCount int out
)
as
declare @StartRow int
declare @EndRow int
-- 计算当前页开始
set @StartRow = (@PageIndex - 1) * @PageSize + 1
-- 计算当前页结束
set @EndRow = @StartRow + @PageSize - 1

-- 建一张内存表用于存储检索结果
declare @temp table
(
AutoID [int] IDENTITY (1, 1) NOT NULL,
RowID [int]
)
-- 执行检索
insert into @temp(RowID)
select RowID from UserGoldHistory
where left(DateTimeTag,10) between @StartDate and @EndDate

set @RowCount = @@ROWCOUNT

select * from UserGoldHistory where RowID in (
select RowID from @temp where AutoID between @StartRow and @EndRow)

sql2005
create proc proc_Split
-- 设置每页的
@page_size int,
-- 设置当前页
@page_current int,
-- 总记录数
@rows_count int out
as

select @rows_count=count(UserName) from ForumUser

DECLARE @start_row_num int
DECLARE @end_row_num int
-- 设置开始
SET @start_row_num = (@page_current - 1) * @page_size + 1
-- 设置结束
SET @end_row_num = @start_row_num + @page_size - 1;

WITH temptesttable AS
(
SELECT ROW_NUMBER() OVER(ORDER BY UserName) AS row_number, *
FROM ForumUser
)
SELECT * from temptesttable
WHERE row_number BETWEEN @start_row_num AND @end_row_num

转载于:https://www.cnblogs.com/loveanytime/archive/2009/07/06/1517709.html


http://www.niftyadmin.cn/n/3297883.html

相关文章

Redis集群技术分类

前言 诚如开篇文章所言&#xff0c;高效运维包括管理的专业化和技术的专业化。前两篇我们主要在说些管理相关的内容&#xff0c;本篇说一下技术专业化。希望读者朋友们能适应这个转换&#xff0c;谢谢。 互联网早在几年前就已进入Web 2.0时代&#xff0c;对后台支撑能力的要求&…

Pages.Instance is null when installing in subdirectory(ScrewTurn Wiki)

“/”应用程序中的服务器错误。 Pages.Instance is null 说明: 执行当前 Web 请求期间&#xff0c;出现未处理的异常。请检查堆栈跟踪信息&#xff0c;以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.InvalidOperationException: Pages.Instance…

C# DES

using System;//这个是使用DES的基础using System.Security.Cryptography;//这个是处理文字编码的前提using System.Text;//以“流”的形式处理文字&#xff0c;也是微软DES算法要求的using System.IO;/// <summary>/// DES加密方法/// </summary>/// <param na…

raft算法与paxos算法相比有什么优势,使用场景有什么差异?

raft利用日志连续性对Paxos做了大量很好的简化&#xff0c;但是其中有一点有很强的误导性&#xff0c;就是新任leader对于旧日志的处理&#xff0c;他的原文描述是“Raft uses a simpler approach where it guarantees that all the committed entries from previous terms are…

前端词汇大全

A absolute 绝对的active 活动的&#xff0c;激活的&#xff0c;<a>标记的一个伪类align 对齐alpha 透明度&#xff0c;半透明anchor 锚记<a>标记是这个单词的缩写arrow 箭头auto 自动Bbackground 背景border 边框banner 页面上的一个横条both 二者都是clear 属性的…

ActiveReports for .NET 简单使用

一. ActiveReports for .net的主要功能介绍 支持ASP.NET-ActiveReports在WebForms应用程序中通过使用ASP.NET 服务器控件来使用。这个控件支持分布式web报表&#xff0c;可使用HTML&#xff0c;ActiveX&#xff0c;.NET 和PDF浏览器。 完全代码集成-使用Microsoft Visual S…

基于ASP.NET的开源Blog程序总结

转自&#xff1a;http://www.livelog.org/article.aspx?id2 .Text http://www.telligentsystems.com/Solutions/Forums/ 多用户 ASP.NET 1.1 SQL Server 2000 开源 更新情况&#xff1a; 英文原版已经并入Community Server。博客园&#xff08;http://cnblogs.com &#xff0…

大数据下的用户行为分析

1. Consumer behaviour is the study of when&#xff0c;why&#xff0c;how and where people do or dont buy a product。 用户行为一般指用户通过中间资源&#xff0c;购买、使用和评价某种产品的记录。同时辅以用户、资源、产品自身及环境的信息。 用户行为记录一般可以表…