Last active
March 7, 2018 16:14
-
-
Save mmmcorpsvit/e758b3ed78f64fe52751da5d39866762 to your computer and use it in GitHub Desktop.
Postgres, "JOIN table if execute condition" in single query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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