Php 获取最后一张海报的线程+用户名
所以,我正在写一个小论坛,我想列出以下内容 线程主题 启动线程的用户的用户名 开始的日期 最后一个在线程中写入的用户的用户名 上次投寄日期 我有三张桌子 帐目Php 获取最后一张海报的线程+用户名,php,mysql,forum,Php,Mysql,Forum,所以,我正在写一个小论坛,我想列出以下内容 线程主题 启动线程的用户的用户名 开始的日期 最后一个在线程中写入的用户的用户名 上次投寄日期 我有三张桌子 帐目 +---------------+ | id | username | |---------------+ | 1 | blargh | | 2 | hest | +---------------+ 线程 +----+-------+------+---------+ | id | topic | user | the
+---------------+
| id | username |
|---------------+
| 1 | blargh |
| 2 | hest |
+---------------+
线程
+----+-------+------+---------+
| id | topic | user | thedate |
+----+-------+------+---------+
| 5 | Yarr | 1 | bleh |
+-------------------+---------+
职位
我想要的是:
+----+-------+----------+---------+--------------------+----------------+
| id | topic | username | thedate | last_post_username | last_post_date |
+----+-------+----------+---------+--------------------+----------------+
| 5 | Yarr | blarg | bleh | hest | bbdate |
+----+-------+----------+---------+--------------------+----------------+
以下是我目前得到的信息:
SELECT
forum_threads.id AS id,
forum_threads.topic AS topic,
forum_threads.time AS time,
accounts.username AS username,
Max(forum_posts.id) AS latest_post_id,
forum_posts.`user` AS `user`,
forum_posts.timeposted AS last_post_time
FROM
((forum_threads
JOIN forum_posts ON ((forum_posts.thread = forum_threads.id)))
JOIN accounts ON ((forum_threads.`user` = accounts.id)))
我似乎无法获取最后一张海报的用户名和所述帖子的时间-我在您的模式中没有看到任何链接帖子到线程的内容。我的答案是假设在帖子中有一个额外的列叫做threadid 对于这个问题,我见过的最常见的解决方案是跟踪threads表中最近一篇文章的ID,可能还有用户ID和用户名。如果您只需要ID,就可以轻松获取最新帖子:
SELECT threadid, MAX(id) FROM posts WHERE <...> GROUP BY threadid
但是没有有效的方法从该查询中获取关联的时间或用户ID。我能找到的最接近的就是这一团糟:
SELECT threadid, id, user, username, thedate FROM posts
WHERE posts.id IN (
SELECT threadid, MAX(id) FROM posts WHERE <...> GROUP BY threadid
)
这在MySQL上是非常低效的-优化器在子查询上完全崩溃,并带有一个GROUPBY。在一个不到100个线程的测试数据库上,查询大约需要300毫秒。只要咬紧牙关,通过将最新帖子的信息存储在线程中来对数据库进行非规范化,一切都会好起来。为什么不使用已经在网络上运行多年的成熟论坛软件呢?你的表和你想要的与你的查询不太匹配,这使得为您编写一个好的答案变得更加困难,但要获得您想要的答案,最简单的方法可能是添加一个where条件,该条件要求forum_posts.timeposted等于一个子查询,该子查询返回forum_posts的max timeposted,其中thread=forum_threads.id。查询上面的所有内容都描述了我的问题。这个查询更像是一个我得到了这么远的东西。啊,是的,你是对的,post表中应该有一个threadid列。
SELECT threadid, id, user, username, thedate FROM posts
WHERE posts.id IN (
SELECT threadid, MAX(id) FROM posts WHERE <...> GROUP BY threadid
)