MySQLjoin,ORDER BY RAND()然后sortingASC(最好使用Sequelize)

我想帮助这个MySQL查询。 理想情况下,我会使用node.js Sequelize ORM生成它。

这些表格是:

Questions: id, question Answers: id, question_id, answer 

我的续集代码是:

 models.questions.findAll({ where: { id: { $notIn: not_in } }, order: [['id','ASC'], [models.answers, 'id', 'ASC']], attributes: ['id', 'question'], include: [{ model: models.answers, attributes: ['id', 'question_id', 'answer'], }] }) 

not_in设置为-1 ,Sequelize会生成以下查询:

 SELECT `questions`.`id`, `questions`.`question`, `answers`.`id` AS `answers.id`, `answers`.`question_id` AS `answers.question_id`, `answers`.`answer` AS `answers.answer` FROM `questions` AS `questions` LEFT OUTER JOIN `answers` AS `answers` ON `questions`.`id` = `answers`.`question_id` WHERE `questions`.`id` NOT IN ( -1 ) ORDER BY `questions`.`id` ASC, `answers`.`id` ASC 

结果在:

 id | question | answers.id | answers.question_id | answers.answer 13 | first question | 17 | 13 | 1st answer 13 | first question | 23 | 13 | 2nd answer 13 | first question | 24 | 13 | 3rd answer 14 | second question | 18 | 14 | 1st answer 14 | second question | 21 | 14 | 2nd answer 14 | second question | 22 | 14 | 3rd answer 15 | third question | 19 | 15 | 1st answer 15 | third question | 20 | 15 | 2nd answer 

我想这个结果,但随机sorting的问题。

所以,而不是13,14和15,它可能是answers.id ,但答案仍然与他们的问题alignment,并按answers.idsorting。

希望任何指针的Sequelize代码或MySQL查询来获得这样的结果。 谢谢!

我已经尝试在各个地方添加ORDER BY RAND() ,但最终还是要洗牌。

PS另外,以前我只需要随机挑选一个问题就可以了,我使用了这个问题:

 SELECT `questions`.`id` AS `question_id`, `questions`.`question` AS `question`, `answers`.`id` AS `answer_id`, `answers`.`answer` AS `answer` FROM (SELECT `questions`.`id`, `questions`.`question` FROM `questions` AS `questions` WHERE (SELECT `question_id` FROM `answers` AS `answers` WHERE `questions`.`id` = `answers`.`question_id` AND questions.id NOT IN ( -1 ) LIMIT 1) IS NOT NULL ORDER BY RAND() LIMIT 1) AS `questions` INNER JOIN `answers` AS `answers` ON `questions`.`id` = `answers`.`question_id` ORDER BY `answers`.`question_id`, `answers`.`id` 

哪个会返回,例如:

 id | question | answers.id | answers.question_id | answers.answer 14 | second question | 18 | 14 | 1st answer 14 | second question | 21 | 14 | 2nd answer 14 | second question | 22 | 14 | 3rd answer 

在普通的MySQL中:

 SELECT ... FROM ( SELECT RAND() AS rnd, id FROM questions ) AS r JOIN questions AS q ON q.id = r.id JOIN answers AS a ON a.question_id = q.id ORDER BY r.rnd, a.id