我有一张表Stories
和一张表Post
。每个Story
包含多个Posts
(Story.hasMany(models.Post);
,Post.belongsTo(models.Story);
)
我想要实现的是列出Posts.createdAt
排序的前10个故事。因此,第一个条目可能是最古老的故事,但有一个非常新的帖子。
我现在正在尝试的是以下内容:
var options = {
limit: 10,
offset: 0,
include: [{
model: models.sequelize.model('Post'),
attributes: ['id', 'createdAt'],
required: true
}],
order: [
[models.sequelize.model('Post'), 'createdAt', 'DESC'],
['createdAt', 'DESC']
],
attributes: ['id', 'title', 'createdAt']
};
Story.findAll(options)...
这给了我这个SQL查询:
SELECT "Story".*, "Posts"."id" AS "Posts.id", "Posts"."createdAt" AS "Posts.createdAt"
FROM (SELECT "Story"."id", "Story"."title", "Story"."createdAt"
FROM "Stories" AS "Story"
WHERE ( SELECT "StoryId"
FROM "Posts" AS "Post"
WHERE ("Post"."StoryId" = "Story"."id") LIMIT 1 ) IS NOT NULL
ORDER BY "Story"."createdAt" DESC LIMIT 10) AS "Story"
INNER JOIN "Posts" AS "Posts" ON "Story"."id" = "Posts"."StoryId"
ORDER BY "Posts"."createdAt" DESC, "Story"."createdAt" DESC;
这里的问题是,如果第11个条目有一个非常新的帖子,它不会显示在前10个列表中。
如何获得由Posts.createdAt
订购的有限故事列表?
答案 0 :(得分:2)
为什么使用两个嵌套的子选择?这无效,可能会产生昂贵的嵌套循环,但仍然无法返回您要查找的内容。
首先,您可以交叉加入故事和帖子,按帖子的创建时间戳排序。但这仍然可以扫描整个表格。
看看这个演示文稿: http://www.slideshare.net/MarkusWinand/p2d2-pagination-done-the-postgresql-way 但我不知道,你怎么能把它带入你的模型: - (