MySQL:连接4个表,结果正确

时间:2016-05-18 11:49:58

标签: mysql

我的数据库中有四个表用于编写一个简单的论坛。

主题:

topic_ID | name | description

主题:

thread_ID | topic_ID | name | description

消息:

message_ID | thread_ID | title | message | date | user_ID

用户:

user_ID | name | email | username

我想运行一个查询来执行以下操作: 显示可用主题,与每个主题关联的线程数,与每个主题关联的消息数,发布的最新消息日期以及发布消息的用户。

结果的一行会说:

Topic: Admin
Threads: 4
Posts: 50
Newest message: 2016/05/18 by pixelled

我从这开始(有效):

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'
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

但是此查询的结果显示了总计列的错误值。

添加users表有效:

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

请帮我完成此查询,以便在总计列中显示正确的值。

这是小提琴: http://sqlfiddle.com/#!9/0f926

2 个答案:

答案 0 :(得分:0)

尝试

Hello from Java

se = Oracle Nashorn
se = 1.8.0_74
se = ECMAScript
se = ECMA - 262 Edition 5.1
se = [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript]

答案 1 :(得分:0)

这是给出正确结果的查询:

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

它复制了线程表,因为它已连接两次。