Sequelize使用ROW_NUMBER()而不是OFFSET和FETCH

时间:2015-10-11 15:01:25

标签: sql sql-server node.js sequelize.js

我注意到使用(offset, fetch)和rownumber时的不同行为。

当我使用行号时,它会返回我期望的结果。

所以我的续集查询如下所示:

 ClanModel.findAll({
    order: [["Wins", "DESC"]],
    offset: page * 5,
    limit: 5
 })

从第一行开始的SQL查询

SELECT 
    [clid] AS [ClanId], [Name], [Wins], [Losses], 
    [totalPoint] AS [TotalPoints] 
FROM 
    [Clan] AS [Clan] 
ORDER BY 
    [Clan].[Wins] DESC 
    OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY;

结果:

[ { Name: 'Test6'},
  { Name: 'Test5'},
  { Name: 'Test4'},
  { Name: 'Test3'},
  { Name: 'Test2'} ]

第5个结果后的SQL查询:

SELECT 
    [clid] AS [ClanId], [Name], [Wins], [Losses],
    [totalPoint] AS [TotalPoints] 
FROM 
    [Clan] AS [Clan] 
ORDER BY 
    [Clan].[Wins] DESC 
    OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;

结果:

[ { Name: 'Test5'},
  { Name: 'Test4'},
  { Name: 'Test3'},
  { Name: 'Test2'},
  { Name: 'Test1'} ]

行号查询:

 SELECT 
     [Name], [Wins], [Losses], [TotalPoints] AS [TotalPoints]
 FROM 
     (SELECT
          [clid] AS [ClanId], [Name], [Wins], [Losses],
          [totalPoint] AS [TotalPoints], 
          ROW_NUMBER() OVER (ORDER BY [Wins]) AS RowNum
      FROM 
          [Clan]) as Clan
 WHERE 
     Clan.RowNum BETWEEN 5 AND 10

返回我期望的结果:

Test5
Test6
Test7
Test8
Test9
Test10

我的数据库记录:

Test1
Test2
Test3
Test4
Test5
Test6
Test7
Test8
Test9
Test10

我想使用我的sequelize模型来获取我的数据,而不是使用普通的SQL查询。但我找不到在续集中使用行号的方法。

有没有办法继续使用sequelize来获取我的数据?

1 个答案:

答案 0 :(得分:1)

您没有显示完整的数据。所以,这是一个猜测:你在wins列中有联系。 order by的排序不稳定,甚至不一致,这意味着关系可以按任何顺序返回。所以,通过包含名称来解决这个问题:

SELECT [clid] AS [ClanId], [Name], [Wins], [Losses], [totalPoint] AS [TotalPoints]
FROM [Clan] AS [Clan]
ORDER BY [Clan].[Wins] DESC, Clan.Name
OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;

假设Name是唯一的,这将使排序保持一致。如果这在SQL中有效,那么它应该很容易在sequelize中实现。