Reputation: 485
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?
Upvotes: 0
Views: 578
Reputation: 5947
You need to use the GROUP BY
:
SELECT messages_id
, title
, message
, user_id
, avatar_id
, avatar
, count(*) as commentCount
FROM messages
inner join avatar on messages.user_id = avatar.user_id
left join comments on messages.messages_id = comments.messages_id
GROUP BY messages_id
This should work if:
messages_id
is unique in messages
user_id
is unique in avatar
Otherwise you need to specify the value you want to get.
Edited:
I wrote inner join
for avatar
table thinking in that all users have an avatar. If this is not true should be left join
like in your query.
Second try
Maybe the error was that the group by
should be messages.messages_id
instead of messages_id
. In fact in others RDMBS this is an error:
ERROR: column reference "messages_id" is ambiguous
I'm going to be more precise:
SELECT m.messages_id as id
, min(m.title) as title
, min(m.message) as message
, min(m.user_id) as user_id
, min(a.avatar_id) as avatar_id
, min(a.avatar) as avatar
, count(c.comments_id) as commentCount
FROM messages as m
left join avatar as a on m.user_id = a.user_id
left join comments as c on m.messages_id = c.messages_id
GROUP BY m.messages_id
All the min
could 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 type min
or max
.
I change join with avatar to be left join
. Probably not all users have an avatar.
Upvotes: 1