I have 3 tables. One for users, one for posts, and a join table linking the two other tables.
Here’s some sample data from the join table.
| id | user_id | post_id | timestamp |
|----|---------|---------|-----------|
| 1 | 1 | 1 | 4-17-2012 |
| 2 | 1 | 2 | 4-16-2012 |
| 4 | 2 | 2 | 4-17-2012 |
| 5 | 3 | 1 | 4-16-2012 |
|____|_________|_________|___________|
I want to write a SELECT query that will do the following:
1) Select all the posts for a user with a timestamp of 4-17-2012
AND
2) If there is no post entry in the join table for that user, select those posts as well.
So…
For user_id = 1, post 1 would be selected, but not post 2, because post 2 is not 4-17-2012
For user_id = 2, both posts would be selected, post 1 because there is no entry for user_id = 2 and post_id = 1, and post 2 because it is 4-17-2012
For user_id = 3, post 1 would not be returned, but post 2 would be, because there is no entry for user_id = 3 and post_id = 2.
Here’s an example of what I’ve been trying:
SELECT * FROM posts AS p
LEFT JOIN posts_users as pu ON ( p.post_id = pu.post_id )
WHERE ((pu.user_id = $user_id AND pu.timestamp = 4-17-2012) OR (pu.post_id IS NULL)
If there was a post_id = 3 row in posts, then it would have NULL for all posts_users columns, because of the LEFT JOIN, which helps satisfy #2. But if there’s anyone at all with a posts_users entry for post_id = 3, then there will be no NULL. Is there a way in MySQL that we can have the logic for #2?
I’m doing this all in a framework that was already written out in PHP, and in a way that would make it very difficult for me to have to deal with using PHP to filter the returned results. Trust me on that one. Is there a way for me to use an SQL statement to accomplish this, or do I have to try and make a workaround in PHP after I get the results of some other query?
Thanks.
Would this work?
select * from user left outer join posts_users on user.id = posts_users.user_id left outer join posts on posts.id = posts_users.post_id where timestamp = ‘4-17-2012’ or timestamp = NULL