Hassan Munir Hassan Munir - 4 months ago 14
MySQL Question

Want to query in array and get result of ids that been passed into query

I made a query which returns me array of ids. like below :

PsychographicsAnswer.group('psychographics_question_id')
.order('count(*) DESC')
.limit(5)
.pluck(:psychographics_question_id)


this return me following result

[175, 174, 176, 173, 172]


Now i want to find question with same ids and exactly in same order. I am querying in following way.

PsychographicsQuestion.where(:id=>PsychographicsAnswer
.group('psychographics_question_id')
.order('count(*) DESC')
.limit(5)
.pluck(:psychographics_question_id))
.pluck(:id)


this return me following result:

[172, 173, 174, 175, 176]


As you can see ids not in order like i pass in query. I want to get result exactly in same fashion as i querying in.

Answer

If you want to order questions according to number of its associated answers then I think you can do like this

Question
  .joins(:answers)
  .select("users.*, count(annswers.id) as scount")
  .group("questions.id")
  .order("scount DESC")
Comments