I am designing a site like pinterest ( for study ) and I want to know what query I have to do at the homepage to show the user’s stream.
I have created these 6 tables:
users
boards
pictures
boards_pictures ( many-to-many table )
followers
comments
And in home, I do this query to get all followers’ pictures.
SELECT users.username, pictures.link, comments.comment, boards.title
FROM boards_pictures, pictures, followers, users, comments, boards
WHERE ( boards_pictures.id_user = followers.id_following )
AND ( boards_pictures.id_picture = pictures.id )
AND ( followers.id_user = $_session['userid'] )
AND ( users.id = followers.id_following )
AND ( comments.picture_id = pictures.id )
AND ( boards.id = boards_pictures.boards_id )
Is there a way to avoid this complex query ( a JOIN with 6 tables ) ?
Here’re the DDL statements deduced from your query:
You’re mixing column naming styles here, compare
users.id,followers.id_user,comments.picture_idandboard_pictures.id_picture(last 2 are quite misleading). The more tables you’ll have, the more attention you’ll have to pay on how column is named. It’s better to stick to a single common pattern,picture_idoruser_idbeing most appropriate in my view.Your query is not complicated, except you’re using implicit join notation. It is not the recommended way, as there’s a chance to miss some predicates and end up with Cartesian product of 2 (or more) tables.
Your query can be rewritten like this:
As you see now, query is really simple and has only one predicate.
I’ve created a testbed without data on SQL Fiddle.
In my view your structure is quite good. There’s no need to change neither table design nor this query.