所以我有表 ForumRooms
、ForumTopics
和 ForumPosts
,它们很容易解释。
目前,我正在更改对主论坛房间页面的查询,以便能够获取存储在 ForumPosts
中的最后发帖时间和用户。
表结构
论坛室
| id | title |
|----------------|
| 1 | Room 1 |
| 2 | Room 2 |
论坛主题
| id | title | forum_room_id |
|------------------|-----------------|
| 1 | Thread 1 | 1 |
| 2 | Thread 2 | 2 |
| 3 | Thread 3 | 1 |
论坛帖子
| 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 Time
和Last Post UserID
之外,我可以在 1 个查询中获取所有内容。
由于 ForumPosts.id
上的 ORDER BY
,下面的查询应该给出我需要的,但我认为 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
如何调整我的查询以获取最后两个缺失的数据?
最佳答案
这可能是使用 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
关于MySQL - Order by on multiple left join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587113/