I’m having a problem which I easily solve with php and some queries, but I wanted to make one big query (at least if it’s faster which I believe it should be).
So I have 3 tables and let simplify them some:
topic which has 3 columns
- id
- user_id
- visibility
access which has 2 columns
- topic_id
- user_id
friendship which has 2 columns
- user_id
- friend_id
What I want to do is if a user (we call him watch_id) is trying to watch this topic I want to return the topic if he is allowed to watch or if he is not, return nothing.
He is allowed to watch if any of these is true:
- watch_id == user_id
- visibility == 3
- visiblity == 2 && the friendship table returns a row when friendship.user_id = topic.user_id && friendship.friend_id == watch_id
- visibility == 1 && the access table returns a row when access.topic_id = topic.id && access.user_id == watch_id
As you can see it’s not very hard to do with php and a bunch of queries but in sql only I can’t figure it out. I’ve been trying joins, case and stuff but the logic never adds up. 🙁
So can you guys help me? Or am I stuck with php and lots of queries?
Edit: Hmm, looks like I wasn’t making myself perfectly clear, my bad! He is allowed to watch if any of those requirements is true. Since this is the case I go with left join answer which was easiest to extend. Thanks all!
You should be able to make left joins against the friendship and access tables, so that the joins themselves doesn’t limit the result: