I have this tables:
blogs
id
name
user_id // author - relational to "users"
users
id
nickname
avatar
suscriptions
id
blog_id // relational to "blogs"
user_id // relational to "users"
The idea is to show on the site something like this:
Blogname
Created By Stack
Suscriptions: Overflow, Easy, Robinson, Porter
I was fetching all data from blogs
SELECT
b.id,
b.name,
b.user_id,
u.nickname as user_nickname,
u.avatar as user_avatar
FROM blogs b
LEFT JOIN users u ON b.user_id = u.id
With PHP I created an array with all the blogs ID
, so I can use them with IN operator, like this:
SELECT
s.id,
s.blog_id,
u.nickname,
u.avatar
FROM suscriptions s
LEFT JOIN users u ON s.user_id = u.id
WHERE s.blog_id IN (1, 2, 3)
And then PHP again for sorting the result.
But, is there a better way? I was thinking about using MySQL only and not PHP. Maybe fetch all the data in just one query? Or what would be the best way to get this?
It's important to have in mind that a blog
can have several subscriptions
.
I found this question from 2012 that is a little similar: JOIN three tables and aggregate data from multiple rows for every DISTINCT row in separate column But the OP says it's really slow, so I'm a little lost right now.