2015-10-11 52 views
2

我有一個表Stories和一個表Post。每個Story包含多個PostsStory.hasMany(models.Post);Post.belongsTo(models.Story);查找最後n個協會訂購的條目

我試圖實現是要列出前10個故事由Posts.createdAt訂購。所以有可能第一個入口是最古老的故事,但有一個非常新的Post。

我想要,現在是這樣的:

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訂購的故事列表?

回答

2

爲什麼使用兩個嵌套子查詢?這是無效的,可能會產生昂貴的嵌套循環,並且仍然不會返回您正在尋找的內容。

作爲開始,您可以交叉連接故事和帖子,按帖子創建時間戳排序。但是這仍然可能掃描整個桌子。

看一看這個演示: http://www.slideshare.net/MarkusWinand/p2d2-pagination-done-the-postgresql-way 但我不知道,你怎麼可以把那個到模型:-(

+0

感謝SlideShare上我真的很喜歡省略的想法所抵消。 –