I’ve got a complicated query that I can’t wrap my head around (using either sql or ActiveRecord) Here are my models:
class Contact
has_many :profile_answers
end
class ProfileAnswer
belongs_to :contact
belongs_to :profile_question
end
class ProfileQuestion
has_many :profile_answers
end
I’m trying to find the number of ProfileAnswers for two contacts that have the same value for a particular ProfileQuestion. In other words:
Get the total number of profile answers that two contacts have answered with the same value for a particular profile_question
I don’t want to make multiple queries and filter as I know this is possible with Sql only, i just don’t know how to do it
I had considered a self join of profile_answers on profile_question_id then filtering by value being equal, but i still can’t wrap my head around that. Any help is greatly appreciated.
I think this will do:
And the
JOINseems not be used. So, ifProfileAnswer.profile_question_idisNOT NULL, this will suffice:EDITED for two specific contacts (with ids
id1andid2).Added the
WHEREand changed theCOUNT (DINSTINCT )toCOUNT(*).Perhaps this version with JOIN can be more easily adapted to ActiveRecord.
Using
JOIN