1

I suspect this is a rather common scenario and may show my ineptitude as a DB developer, but here goes anyway ...

I have two tables: Profiles and HiddenProfiles and the HiddenProfiles table has two relevant foreign keys: profile_id and hidden_profile_id that store ids from the Profiles table.

As you can imagine, a user can hide another user (wherein his profile ID would be the profile_id in the HiddenProfiles table) or he can be hidden by another user (wherein his profile ID would be put in the hidden_profile_id column). Again, a pretty common scenario.

Desired Outcome:
I want to do a join (or to be honest, whatever would be the most efficient query) on the Profiles and HiddenProfiles table to find all the profiles that a given profile is both not hiding AND not hidden from.

In my head I thought it would be pretty straightforward, but the iterations I came up with kept seeming to miss one half of the problem. Finally, I ended up with something that looks like this:

SELECT "profiles".* FROM "profiles"
LEFT JOIN hidden_profiles hp1 on hp1.profile_id = profiles.id and (hp1.hidden_profile_id = 1)
LEFT JOIN hidden_profiles hp2 on hp2.hidden_profile_id = profiles.id and (hp2.profile_id = 1)
WHERE (hp1.hidden_profile_id is null) AND (hp2.profile_id is null)

Don't get me wrong, this "works" but in my heart of hearts I feel like there should be a better way. If in fact there is not, I'm more than happy to accept that answer from someone with more wisdom than myself on the matter. :)

And for what it's worth these are two RoR models sitting on a Postgres DB, so solutions tailored to those constraints are appreciated.


Models are as such:

class Profile < ActiveRecord::Base
    ...
    has_many :hidden_profiles, dependent: :delete_all

    scope :not_hidden_to_me, -> (profile) { joins("LEFT JOIN hidden_profiles hp1 on hp1.profile_id = profiles.id and (hp1.hidden_profile_id = #{profile.id})").where("hp1.hidden_profile_id is null") }
    scope :not_hidden_by_me, -> (profile) { joins("LEFT JOIN hidden_profiles hp2 on hp2.hidden_profile_id = profiles.id and (hp2.profile_id = #{profile.id})").where("hp2.profile_id is null") }
    scope :not_hidden, -> (profile) { self.not_hidden_to_me(profile).not_hidden_by_me(profile) }
    ...
end

class HiddenProfile < ActiveRecord::Base
    belongs_to :profile
    belongs_to :hidden_profile, class_name: "Profile"
end

So to get the profiles I want I'm doing the following:

Profile.not_hidden(given_profile)

And again, maybe this is fine, but if there's a better way I'll happily take it.

5
  • 2
    Can you show the models, so we can see the associations?
    – IngoAlbers
    Sep 21, 2015 at 16:24
  • Sure, you just want to see the "has_many/belongs_to" bits? ... though I think they're pretty straightforward.
    – Tydeology
    Sep 21, 2015 at 16:29
  • @Mischa, thanks for the edit! Couldn't quickly figure out how to make it look like that. ;-)
    – Tydeology
    Sep 21, 2015 at 16:30
  • Yes. Just the names of the models and the associations should be enough. Then you could probably use an active record query, which is in my opinion a bit cleaner in a rails project.
    – IngoAlbers
    Sep 21, 2015 at 16:31
  • Updated as requested.
    – Tydeology
    Sep 21, 2015 at 16:43

2 Answers 2

1

If you want to get this list just for a single profile, I would implement an instance method to perform effectively the same query in ActiveRecord. The only modification I made is to perform a single join onto a union of subqueries and to apply the conditions on the subqueries. This should reduce the columns that need to be loaded into memory, and hopefully be faster (you'd need to benchmark against your data to be sure):

class Profile < ActiveRecord::Base
  def visible_profiles
    Profile.joins("LEFT OUTER JOIN (
      SELECT profile_id p_id FROM hidden_profiles WHERE hidden_profile_id = #{id}
      UNION ALL
      SELECT hidden_profile_id p_id FROM hidden_profiles WHERE profile_id = #{id}
    ) hp ON hp.p_id = profiles.id").where("hp.p_id IS NULL")
  end
end

Since this method returns an ActiveRecord scope, you can chain additional conditions if desired:

Profile.find(1).visible_profiles.where("created_at > ?", Time.new(2015,1,1)).order(:name)
1
  • Thanks for this! I think you hit the nail on the head! I ran EXPLAIN on it and it does seem more performant! I'll give it another hour or so for other ideas then come back and mark this as answered. Thanks again!
    – Tydeology
    Sep 21, 2015 at 16:54
1

Personally I've never liked the join = null approach. I find it counter intuitive. You're asking for a join, and then limiting the results to records that don't match.

I'd approach it more as

SELECT id FROM profiles p
WHERE 
NOT EXISTS 
 (SELECT * FROM hidden_profiles hp1 
  WHERE hp1.hidden_profile_id = 1 and hp1.profile_id = p.profile_id)
AND
  NOT EXISTS (SELECT * FROM hidden_profiles hp2 
  WHERE hp2.hidden_profile_id = p.profile_id and hp2.profile_id = 1)

But you're going to need to run it some EXPLAINs with realistic volumes to be sure of which works best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.