一度に3つのテーブルからデータを取得しようとしています。テーブルは次のようになります。
カテゴリ
id
category
messageid
メッセージ
id
title
message
コメント
id
messageid
message
私が取得しようとしているのは、1つのメッセージ(WHERE
idに基づく句があるため3
)、3つのカテゴリ(メッセージにリンクされた3つのカテゴリがあるため)、および2つのコメント(メッセージにリンクされた2つのコメントがあるため)です。
次のクエリを使用してデータを取得しようとしています。
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
ただし、このクエリを実行すると、6つの結果が得られます。
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
次のような結果を期待したところ:
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
たった3行で、必要なすべてのデータを取得できるはずです。これも可能ですか?私はそれを完全に間違っていますか?