【问题标题】:How to modify this query for pagination fetching?如何修改此查询以获取分页?
【发布时间】:2012-10-11 06:42:10
【问题描述】:

这是一个非常复杂的查询,所以我在这里遇到了困难。如果您帮助我,我将不胜感激。

select AvgLevel,TotalCount,tblPokedex.PokemonId,Name,Type1,Type2,Hp,tblPokedex.Attack,tblPokedex.Defense,tblPokedex.SpAttack,tblPokedex.SpDefense,tblPokedex.Speed,(Hp+tblPokedex.Attack+tblPokedex.Defense+tblPokedex.SpAttack+tblPokedex.SpDefense+tblPokedex.Speed) as TotalStats 
from tblPokemonStats,tblAvailablePokemons,tblPokedex 
left join tblUsersPokemons on tblPokedex.PokemonId=tblUsersPokemons.PokemonId 
where tblPokemonStats.PokemonId=tblPokedex.PokemonId 
group by tblPokedex.PokemonId,tblPokedex.Name,tblPokedex.Type1,tblPokedex.Type2,tblPokedex.Hp,tblPokedex.Attack,tblPokedex.Defense,tblPokedex.SpAttack,tblPokedex.SpDefense,tblPokedex.Speed,tblPokemonStats.AvgLevel,tblPokemonStats.TotalCount  
order by PokemonId asc

好吧,我想做的是例如在前 100 名和 150 名之间进行选择

我该怎么做?

【问题讨论】:

    标签: sql tsql pagination sql-server-2008-r2 row-number


    【解决方案1】:

    这是一种方法 - 添加 row_number 列并对其进行过滤:

    select AvgLevel /*...*/
    from (
        select AvgLevel /*...*/, row_number() over (order by PokemonId) rownum 
        from tblPokemonStats,tblAvailablePokemons,tblPokedex 
        left join tblUsersPokemons on tblPokedex.PokemonId=tblUsersPokemons.PokemonId 
        where tblPokemonStats.PokemonId=tblPokedex.PokemonId 
        group by /* etc ... */
    ) A
    where A.rownum > 100 and A.rownum <= 150
    

    row_number 听起来像 - 它为您的行编号。

    这是另一种可能性 - 假设您想要 X 到 Y 行。您可以根据您的订单选择TOP Y 行。然后使用该子查询并根据相反的顺序选择TOP Y-X。 假设 X = 100 且 Y = 150:

    select top 50 *
    from (
        select top 150 PokemonId
        from tblPokemonStats
        order by PokemonId
    ) A
    order by PokemonId desc
    

    就性能而言,我不确定哪个会更好。我的直觉说ORDER BY 方法更适合“前面”附近的页面,可以这么说,但row_number() 更适合后面的页面(高 X 和 Y)。这只是一个猜测 - 运行一些测试,看看什么对你有用。

    【讨论】:

    • 好的,这是可行的,但我检查了 IO 计数,它非常高。我想知道还有其他更好的性能解决方案
    • 您不能在 TOP 表达式中使用变量 - 您需要将其替换为实际数字。
    • 不,我的意思是在我的情况下该方法不适用于分页:)
    • 嗯,你可以在TOP 表达式中使用一个变量,但是语法会略有不同TOP(@var)
    猜你喜欢
    • 2013-05-27
    • 2014-09-30
    • 2023-04-02
    • 2020-08-21
    • 1970-01-01
    • 2011-12-13
    • 2019-06-22
    • 2021-03-12
    • 1970-01-01
    相关资源
    最近更新 更多