私は、私がコーディングしている簡単なフォーラムのために私のDBに4つのテーブルを持っています。MySQL:正しい結果で4つのテーブルを結合する
トピック:
topic_ID | name | description
スレッド:
thread_ID | topic_ID | name | description
メッセージ:
message_ID | thread_ID | title | message | date | user_ID
ユーザー:
user_ID | name | email | username
次のように1つのクエリを実行します。 利用可能なトピック、各トピックに関連付けられたスレッドの数、各トピックに関連付けられたメッセージの数、最新のメッセージの投稿日付、および投稿したユーザーを表示します。 (働いている)私はこれを始め
Topic: Admin
Threads: 4
Posts: 50
Newest message: 2016/05/18 by pixelled
:
だから、結果の1行が何かのように言うだろう
SELECT topics.topic_id, topics.name, count(threads.topic_id) AS 'totals', MAX(messages.date) AS 'Newest'
FROM topics
LEFT JOIN threads
ON topics.topic_id = threads.topic_id
LEFT JOIN messages
ON messages.thread_id = threads.thread_id
GROUP BY threads.topic_id
:私はその後、メッセージテーブルを追加
SELECT topics.topic_id, topics.name, count(threads.topic_id) AS 'totals'
FROM topics
LEFT JOIN threads
ON topics.topic_id = threads.topic_id
GROUP BY threads.topic_id
しかし、このクエリの結果は、合計列に間違った値を示しています。ユーザーテーブルを追加
は動作します:
SELECT topics.topic_id, topics.name, count(threads.topic_id) AS 'totals', MAX(messages.date) AS 'Newest', users.username
FROM topics
LEFT JOIN threads
ON topics.topic_id = threads.topic_id
LEFT JOIN messages
ON messages.thread_id = threads.thread_id
LEFT JOIN users
ON users.user_ID = messages.user_ID
GROUP BY threads.topic_id
正しい値が合計欄に表示されるように、私はこのクエリを完了するのに助けてください。それは参加したため
SELECT topics.topic_id, topics.name, topics.description, count(threads.topic_id) AS 'totals', MAX(m.date) AS 'Newest', users.username
FROM topics
LEFT JOIN threads
ON topics.topic_id = threads.topic_id
LEFT JOIN
(
SELECT thread_id, date, user_id
FROM messages
GROUP BY thread_id
) m
ON m.thread_id = threads.thread_id
LEFT JOIN users
ON users.id = m.user_id
GROUP BY threads.topic_id
それは、スレッドテーブルを複製した http://sqlfiddle.com/#!9/0f926
あなたはSQLファイルを提供できますか? ? –