首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何指定要排序/限制的字段?

如何指定要排序/限制的字段?
EN

Stack Overflow用户
提问于 2016-03-02 17:07:37
回答 1查看 1.1K关注 0票数 5

我的问题是:

代码语言:javascript
复制
    db.Question.findAll
      where:
        id:
          $notIn: if questionIds.length > 0 then questionIds else [-1]
        TopicId: topicCount.id
        PassageId: null
        status: 'active'
        level:
          $lte: startLevel
          $gte: endLevel
      include: [
        model: db.Answer
      ]
      order: [db.Sequelize.fn 'RANDOM']
      limit: questionSections[sectionIndex].goal * 2

这将生成以下查询:

代码语言:javascript
复制
SELECT "Question".*, 
       "answers"."id"         AS "Answers.id", 
       "answers"."answertext" AS "Answers.answerText", 
       "answers"."iscorrect"  AS "Answers.isCorrect", 
       "answers"."createdat"  AS "Answers.createdAt", 
       "answers"."updatedat"  AS "Answers.updatedAt", 
       "answers"."questionid" AS "Answers.QuestionId" 
FROM   (SELECT "Question"."id", 
               "Question"."status", 
               "Question"."questiontext", 
               "Question"."level", 
               "Question"."originalid", 
               "Question"."createdbyuserid", 
               "Question"."editedbyuserid", 
               "Question"."createdat", 
               "Question"."updatedat", 
               "Question"."instructionid", 
               "Question"."topicid", 
               "Question"."subjectid", 
               "Question"."passageid" 
        FROM   "questions" AS "Question" 
        WHERE  "Question"."id" NOT IN ( -1 ) 
               AND "Question"."topicid" = '79' 
               AND "Question"."passageid" IS NULL 
               AND "Question"."status" = 'active' 
               AND ( "Question"."level" <= 95 
                     AND "Question"."level" >= 65 ) 
        LIMIT  300) AS "Question" 
       LEFT OUTER JOIN "answers" AS "Answers" 
                    ON "Question"."id" = "answers"."questionid" 
ORDER  BY Random(); 

这一切都很好,但我希望ORDER BY应用于内部查询(SELECT "Question"."id", "Question"."status",)。我怎样才能做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-06 14:42:03

您是否尝试过定义自定义作用域 (比如random ),它随机地对问题进行排序,然后在查询中使用该范围,例如:

代码语言:javascript
复制
db.Question.scope('random').findAll({
  where:{
    ..........
  },
  include: [{
    model: db.Answer
  }],
  //order: [db.Sequelize.fn 'RANDOM'] <<<<<<< moved to custom scope
  limit: questionSections[sectionIndex].goal * 2
 })
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35753733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档