0

I have tables posts and users

basically i want to query if the column privacy of posts table is 0 it means post is public and i want to show this to everyone. but if privacy column is 1,2,3,4 it means this post is only for users with ID 1, 2, 3 and 4

juergen d
  • 201,996
  • 37
  • 293
  • 362

1 Answers1

0

This is not a conditional problem it's a sql join through table association problem.

You need to create a join table that associates a post to a user. You can then use a join to select posts based upon their assignment to a user.

The SQL might look something like this

To select posts assigned to user ID = 4

SELECT * FROM `posts` 
    LEFT JOIN `posts_users` ON (`posts`.`id` = `posts_users`.`post_id`) 
    WHERE `posts_users`.`user_id` = 4;

You have also made the assumption that if a post has no users assigned to it, then it's a public post. That requires a check for NULL associations.

SELECT * FROM `posts` 
    LEFT JOIN `posts_users` ON (`posts`.`id` = `posts_users`.`post_id`) 
    WHERE `posts_users`.`user_id` IS NULL;

If you want to find both public and associated posts, then you use a logical OR to match both rules.

SELECT * FROM `posts` 
    LEFT JOIN `posts_users` ON (`posts`.`id` = `posts_users`.`post_id`) 
    WHERE `posts_users`.`user_id` = 4
       OR `posts_users`.`user_id` IS NULL;
Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • i want the query outcome, posts for person whos id is in PRIVACY column OR privacy column be 0(public) so the person sees it. – user2765602 Jun 27 '14 at 13:45
  • `posts_users` is a third data table that defines `post_id` and `user_id` columns. For each user that owns a post there needs to be a record to define that association. – Reactgular Jun 27 '14 at 13:53
  • http://stackoverflow.com/questions/3029454/sql-query-through-an-intermediate-table – Reactgular Jun 27 '14 at 13:54