php - How to write IF ELSE statements in MySQL -
i have tables posts
, users
basically want query if column privacy
of posts
table 0
means post public
, want show everyone. if privacy
column 1,2,3,4
means post users id 1, 2, 3 , 4
this not conditional problem it's sql join through table association problem.
you need create join table associates post user. can use join select posts based upon assignment user.
the sql might this
to select posts assigned user id = 4
select * `posts` left join `posts_users` on (`posts`.`id` = `posts_users`.`post_id`) `posts_users`.`user_id` = 4;
you have made assumption if post has no users assigned it, it's public post. requires check null associations.
select * `posts` left join `posts_users` on (`posts`.`id` = `posts_users`.`post_id`) `posts_users`.`user_id` null;
if want find both public , associated posts, use logical or match both rules.
select * `posts` left join `posts_users` on (`posts`.`id` = `posts_users`.`post_id`) `posts_users`.`user_id` = 4 or `posts_users`.`user_id` null;
Comments
Post a Comment