所以,我正在写一个小论坛,我想列出以下内容
我有三张表
帐户
+---------------+
| id | username |
|---------------+
| 1 | blargh |
| 2 | hest |
+---------------+
线程
+----+-------+------+---------+
| id | topic | user | thedate |
+----+-------+------+---------+
| 5 | Yarr | 1 | bleh |
+-------------------+---------+
帖子
+----+---------+------+---------+--------+
| id | content | user | thedate | thread |
+----+---------+------+---------+--------+
| 8 | aaaa | 1 | aadate | 5 |
+----+---------+------+---------+--------+
| 9 | bbbb | 2 | bbdate | 5 |
+----+---------+------+---------+--------+
我想要的是什么:
+----+-------+----------+---------+--------------------+----------------+
| 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)))
我似乎无法获得最后一张海报的用户名和所述帖子的时间
答案 0 :(得分:0)
首先 - 我没有在架构中看到任何将帖子链接到线程的内容。我的回答是假设posts
中有一个名为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的效率非常低 - 优化器在具有GROUP BY
的子查询上完全崩溃。 (在一百个线程的测试数据库上查询大约需要300毫秒。)只需咬一口,通过在线程中的最新帖子上存储信息来对数据库进行反规范化,一切都会好的。