MySQL - 按多个左连接排序

时间:2015-02-18 15:20:51

标签: mysql sql

所以我有表ForumRoomsForumTopicsForumPosts,它们非常自我解释。

目前我正在更改主论坛会议室页面的查询,以便能够获得最后一次发布时间和用户,存储在ForumPosts


表格结构

ForumRooms

|  id  |  title  |
|----------------|
|  1   | Room 1  |
|  2   | Room 2  |

ForumThreads

|  id  |  title    |  forum_room_id  |
|------------------|-----------------|
|  1   | Thread 1  |  1              |
|  2   | Thread 2  |  2              |
|  3   | Thread 3  |  1              |

ForumPosts

|  id  |  content  |  forum_thread_id |  post_time  |  user_id  |
|------------------|------------------|-------------|-----------|
|  1   | A post 1  |  1               |  15/02/2015 |  1        |
|  2   | A post 2  |  2               |  16/02/2015 |  2        |
|  3   | A post 3  |  1               |  17/02/2015 |  1        |
|  4   | A post 4  |  1               |  18/02/2015 |  2        |


目标

我正在尝试编写1个查询以允许以下格式化输出:

输出

|  ForumRoom  |  Thread Count  |  Post Count  |  Last Post Time  |  Last Post UserID  |
|-------------|----------------|--------------|------------------|--------------------|
|  Room 1     |  2             |  3           |  16/02/2015      |  2                 |
|  Room 2     |  1             |  1           |  18/02/2015      |  2                 |


问题

目前,我可以在Last Post TimeLast Post UserID之外的1个查询中获取所有内容。

以下查询应该根据ORDER BY上的ForumPosts.id给出我需要的内容,但我认为GROUP BY会阻止其按要求运行。

SELECT ForumRooms.title, COUNT(DISTINCT ForumThreads.id), COUNT(ForumPosts.id), ForumPosts.post_time, ForumPosts.user_id
FROM ForumRooms
LEFT JOIN ForumThreads ON ForumRooms.id = ForumThreads.forum_room_id
LEFT JOIN ForumPosts ON ForumThreads.id = ForumPosts.forum_thread_id
GROUP BY ForumRooms.id
ORDER BY ForumPosts.id DESC

如何调整查询以获取最后两个缺失的数据?

1 个答案:

答案 0 :(得分:3)

这可能是使用substring() / group_concat()技巧的好地方:

SELECT ForumRooms.title, COUNT(DISTINCT ForumThreads.id), COUNT(ForumPosts.id), 
       MAX(ForumPosts.post_time),
       SUBSTRING_INDEX(GROUP_CONCAT(ForumPosts.user_id ORDER BY ForumPosts.post_time DESC), ',', 1)
FROM ForumRooms LEFT JOIN
     ForumThreads
     ON ForumRooms.id = ForumThreads.forum_room_id LEFT JOIN
     ForumPosts
     ON ForumThreads.id = ForumPosts.forum_thread_id
GROUP BY ForumRooms.id
ORDER BY ForumPosts.id DESC