Skip to content

Instantly share code, notes, and snippets.

@mmmcorpsvit
Last active March 7, 2018 16:14
Show Gist options
  • Save mmmcorpsvit/e758b3ed78f64fe52751da5d39866762 to your computer and use it in GitHub Desktop.
Save mmmcorpsvit/e758b3ed78f64fe52751da5d39866762 to your computer and use it in GitHub Desktop.
Postgres, "JOIN table if execute condition" in single query
set session my.vars.user_id = 0; -- not entered
set session my.vars.user_id = 1;-- entered, user.id=1
select
*
from
services sv
-- favorite, (join only if user.id > 0)
LEFT JOIN
suser_customuser_favorite_services suf
ON (sv.service_id = suf.service_id AND (
-- не авторизирован
(current_setting('my.vars.user_id')::int = 0 and suf.id=0) OR
-- авторизирован
(current_setting('my.vars.user_id')::int > 0 and suf.customuser_id = current_setting('my.vars.user_id')::int) ))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment