I have 3 different tables:
Messages, Comments and Avatar.
What I would like to do is the following:
Get all Messages in the database, counting for each message the comments and showing the avatar of each user.
This is how the tables are built:
Messages -> messages_id, user_id, title, message
Comments -> comments_id, messages_id, comment
Avatar -> avatar_id, user_id, avatar
I tried the following:
SELECT *, COUNT(comments.comments_id) AS commentCount
FROM messages
LEFT JOIN comments ON messages.messages_id = comments.messages_id
LEFT JOIN avatar on messages.user_id = avatar.user_id
But I get only one row for the messages, the rest is not visible.
Any idea what I’m doing wrong here?
You need to use the
GROUP BY:This should work if:
messages_idis unique inmessagesuser_idis unique inavatarOtherwise you need to specify the value you want to get.
Edited:
I wrote
inner joinforavatartable thinking in that all users have an avatar. If this is not true should beleft joinlike in your query.Second try
Maybe the error was that the
group byshould bemessages.messages_idinstead ofmessages_id. In fact in others RDMBS this is an error:I’m going to be more precise:
All the
mincould be deleted in MySQL if you are sure there is only one value. In standard SQL you must choose the value you want, if there is only one you can typeminormax.I change join with avatar to be
left join. Probably not all users have an avatar.