话题
id | name |
-------------------
1 | bla |
2 | lala |
帖子
topic_id | user | time |
--------------------------------------------
1 | X | 2013-08-09 12:00:00 |
1 | Y | 2013-08-09 13:00:00 |
2 | Y | 2013-08-09 12:00:00 |
--------------------------------------------
用户视图
topic_id | user_id | posts | read |
---------------------------------------------
NULL | NULL | NULL | NULL |
---------------------------------------------
当用户第一次打开论坛时,您需要添加新帖子
INSERT INTO `user_views` (`topic_id`, `user_id`, `posts`, `read`)
VALUES (
(SELECT `id` FROM `topics`),
$_SESSION['user_id'],
(SELECT COUNT(`topic_id`) FROM `posts` GROUP BY `topic_id`),
0
);
于是,变成了:
用户视图
topic_id | user_id | posts | read |
---------------------------------------------
1 | 5 | 2 | 0 |
2 | 5 | 1 | 0 |
---------------------------------------------
用户打开 topic_id = 1,因此帖子会自动阅读(您可能没有跟踪每个帖子的阅读方式)。因此,关于该主题的确切开头:
UPDATE `user_views` SET `read` = (SELECT COUNT(`topic_id`) FROM `posts` WHERE `topic_id` = $_GET['topic_id'] AND user_id = $_SESSION['user_id'];
现在变成了:
用户视图
topic_id | user_id | posts | read |
---------------------------------------------
1 | 5 | 2 | 2 |
2 | 5 | 1 | 0 |
---------------------------------------------
现在在 topic_id=1 中发布了一个新帖子:
帖子
topic_id | user | time |
--------------------------------------------
1 | X | 2013-08-09 12:00:00 |
1 | Y | 2013-08-09 13:00:00 |
2 | Y | 2013-08-09 12:00:00 |
1 | Z | 2013-08-09 14:00:00 |
--------------------------------------------
用户打开论坛,它会检查是否有新主题可以插入帖子并查看,如果没有,则只执行以下操作:
UPDATE `user_views` SET `posts` = (SELECT COUNT(`topic_id`) FROM `posts` WHERE `topic_id` = (SELECT `id` FROM `topics` WHERE `id` = `posts`.`topic_id`) AND user_id = $_SESSION['user_id'];
于是变成了:
用户视图
topic_id | user_id | posts | read |
---------------------------------------------
1 | 5 | 3 | 2 |
2 | 5 | 1 | 0 |
---------------------------------------------
要检索未读帖子,您可以执行以下操作:
SELECT `topic_id`, `user_id`, `posts`-`read` as 'unread' FROM `user_views` WHERE user_id = $_SESSION['user_id'];
这将返回:
用户视图
topic_id | user_id | unread |
----------------------------------
1 | 5 | 1 | // 3-2
----------------------------------
2 | 5 | 1 | // 1-0
----------------------------------
因此,从上次访问开始,用户现在每个主题中只有 1 个新帖子。
我希望你明白这个逻辑。也许有更简单的方法将已经查看的帖子存储在会话或 cookie 中,但这对我来说似乎不可靠,所以我想一个新表是可以的。
如何在用户访问论坛时首先插入新主题,取决于您的应用逻辑。
当然,查询可能有一些错误,我尽量使它们可行。它们只是示例,您必须使它们适合您的应用程序,即不要直接在查询中注入 $_GET 或 $_SESSION。
PS:我建议id
在表中有自动增量键列POSTS
,这样它会执行得更好,查询也会反对id
,而不是 topic_id 即SELECT COUNT(id) FROM posts