sql - Postgres query to select based on row count and existence -


this might sound involved, please bear me. :)

i have 2 tables: users , profiles. users can have many profiles, filled out when user oauths provider facebook or google. profiles has column source name 'google' or 'facebook', , column profile's public image_url.

if user has associated profile, want use image_url in img tag when display user in list on webpage. if user has multiple profiles, want prefer facebook image on google.

so users, want proper image_url along other user.* attributes. can entirely in 1 postgres query? if so, like?

so far (embarrassingly), have this:

select image_url users join profiles on users.id = profiles.user_id; 

this give me multiple rows if user has connected more 1 profile. i'd modify query that:

  • users without associated profile should have null image_url
  • users have associated google profile should have image url google profile
  • users have associated facebook profile should have image url facebook profile
  • users have both associated facebook profile , google profile should have facebook image url

can sql experts weigh in? thanks!

clarifications:

  • profiles can facebook or google. user can have 1 facebook profile and/or 1 google profile. (that is, user cannot have multiple google profiles nor can have multiple facebook profiles.)

an elegant solution use 2 cte's , coalesce:

with fb (   select user_id, image_url   profiles   profile = 'facebook' ), ggl (   select user_id, image_url   profiles   profile = 'google' ) select users.*, coalesce(fb.image_url, ggl.image_url) users left join ggl on ggl.user_id = users.id left join fb on fb.user_id = users.id 

the first cte gets facebook image_url, if available, second cte gets google image_url. coalesce makes sure facebook image_url selected if present.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -