所以,我有一个表,主题
ThreadNumber | Sticky | Title
1 | 1 | Read This Before Posting!
2 | 0 | Second Topic
3 | 0 | Check This
还有第二张表帖子
ThreadNumber | Author | Timestamp | Body | PostNumber
1 | User1 | 1 | Read up! | 0
1 | User2 | 2 | I see. | 1
2 | User2 | 3 | So tell me what'chu want! | 0
3 | User3 | 5 | Yeah, check this out. | 0
2 | User3 | 7 | What'chu really really want!| 1
2 | User1 | 10 | I'll tell you what I want! | 2
(Posts中的时间戳是当给定用户向db提交注释时PHP time()
函数给出的时间的十位二次整数表示。)所以,当涉及到显示所有论坛帖子时论坛概述页面上的主题,我想要做的是按照发布最后一条评论的顺序显示所有主题。我已经尝试了自己的嵌套MySQL查询(没有解决),所以我开始尝试做一些研究。我找到的任何其他东西都无法让我得到我想要的东西。我觉得this接近了,但我仍然得到了独特的ThreadNumbers给出的所有结果。理想情况下,我会得到的回报是:
ThreadNumber | Title | LastTimestamp
2 | Second Topic | 10
3 | Check This | 5
1 | Read This Before Posting! | 1
非常感谢您阅读本书以及任何可能的[并且非常需要]帮助!
我试过了
SELECT PostNumber, ThreadNumber, Body, Author, Timestamp
FROM (SELECT PostNumber, ThreadNumber, Body, Author, Timestamp
FROM Posts
ORDER BY Timestamp DESC) AS p
GROUP BY ThreadNumber;
它不仅不会返回我真正想要的东西,而且还没有像我预期的那样工作。
答案 0 :(得分:0)
您可以通过以下示例在一个请求中执行此操作
select
Posts.ThreadNumber,
Title,
max(Timestamp)
from Threads
left join Posts on Threads.ThreadNumber = Posts.ThreadNumber
group by Posts.ThreadNumber, Title
order by max(timestamp) desc;
使用
等源数据mysql> select * from Posts;
+--------------+--------+-----------+------+------------+
| ThreadNumber | Author | Timestamp | Body | PostNumber |
+--------------+--------+-----------+------+------------+
| 1 | User1 | 20 | | 0 |
| 2 | User1 | 30 | | 0 |
| 3 | User1 | 10 | | 0 |
| 1 | User1 | 24 | | 0 |
| 2 | User1 | 2 | | 0 |
| 3 | User1 | 200 | | 0 |
+--------------+--------+-----------+------+------------+
6 rows in set (0,00 sec)
和
mysql> select * from Threads;
+--------------+--------+----------+
| ThreadNumber | Sticky | Title |
+--------------+--------+----------+
| 1 | 0 | Thread 1 |
| 2 | 0 | Thread 2 |
| 3 | 0 | Thread 3 |
+--------------+--------+----------+
3 rows in set (0,00 sec)
将输出以下
mysql> select distinct Posts.ThreadNumber, Title, max(Timestamp) from Threads left join Posts on Threads.ThreadNumber = Posts.ThreadNumber group by Posts.ThreadNumber, Title order by max(timestamp) desc;
+--------------+----------+----------------+
| ThreadNumber | Title | max(Timestamp) |
+--------------+----------+----------------+
| 3 | Thread 3 | 200 |
| 2 | Thread 2 | 30 |
| 1 | Thread 1 | 24 |
+--------------+----------+----------------+
3 rows in set (0,00 sec)
但在你的情况下,我将重新开发数据库结构。你的结构中有一些非常糟糕的问题。至少你可以在帖子中添加id字段。现在,您无法在其中设置有效索引,并且对于大数据,您的请求将会变慢。