gpt4 book ai didi

sql - 序列化使用 ROW_NUMBER() 而不是 OFFSET 和 FETCH

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:59 27 4
gpt4 key购买 nike

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

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

所以我的 Sequelize 查询如下所示:

 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 中使用行号的方法。

有没有办法仍然使用sequelize来获取我的数据?

最佳答案

您没有显示完整的数据。所以,这是一个猜测:您在 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 中应该很容易实现。

关于sql - 序列化使用 ROW_NUMBER() 而不是 OFFSET 和 FETCH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33066461/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com