gpt4 book ai didi

php - 按最新帖子的顺序拉取论坛主题

转载 作者:行者123 更新时间:2023-11-29 20:24:16 25 4
gpt4 key购买 nike

所以,我有一张表,Threads

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

(帖子中的时间戳是当给定用户向数据库提交评论时 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;

这不仅不会返回我真正想要的结果,而且也没有按照我预期的方式工作。

最佳答案

您可以通过以下示例在一个请求中完成此操作

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 字段。目前您无法在其中设置有效的索引,并且大数据时您的请求会变慢。

关于php - 按最新帖子的顺序拉取论坛主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39378492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com