I am trying to retrieve data from three tables at once. The tables look like:
categories
id
category
messageid
messages
id
title
message
comments
id
messageid
message
What I am trying to get is 1 message (because I have a WHERE
clause based on id 3
), 3 categories (because there are 3 categories linked to the message) and 2 comments (because there are 2 comments linked to the message).
I'm trying to retrieve the data by usnig the following query:
SELECT categories.category, messages.id, messages.title, messages.message, comments.count, comments.id as commentid, comments.message as commentmessage
FROM categories
RIGHT JOIN
(SELECT id, title, message
FROM messages WHERE messaged.id = 3) messages
ON messages.id = categories.messageid
LEFT JOIN
(SELECT count(id), id, message
FROM comments
GROUP BY id, message) comments
ON messages.id = comments.messageid
ORDER BY article.id DESC
However when running this query I get 6 results:
category id title message count commentid commentmessage
test 3 the title the message 1 6 comment 1
test 3 the title the message 1 5 comment 2
installation 3 the title the message 1 6 comment 1
installation 3 the title the message 1 5 comment 2
question 3 the title the message 1 6 comment 1
question 3 the title the message 1 5 comment 2
Where I expected a result something like:
category id title message count commentid commentmessage
test 3 the title the message 1 6 comment 1
question 3 the title the message 1 5 comment 2
installation 3 the title the message 1 null null
With only three rows I should be able to get all the needed data. Is this even possible? Am I doing it completely wrong ™?