php - 如何计算自定义论坛的留言板中的回复数量?

标签 php mysql join

我正在使用 PHP 和 MySQL 开发一个自定义论坛。在这种情况下,我有三个主要表:板、线程和消息。我想统计一个板上的消息数量。线程表有一列名为“first_msg_id”,它是对该线程的第一条消息的引用。我的查询不应计算此消息。

CREATE TABLE IF NOT EXISTS `forum_messages` (
  `message_id` int(15) NOT NULL AUTO_INCREMENT,
  `thread_id` int(15) NOT NULL,
  `author_id` int(15) NOT NULL,
  `modifier_id` int(15) DEFAULT NULL,
  `content` text NOT NULL,
  `date_posted` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `date_modified` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`message_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `forum_threads` (
  `thread_id` int(15) NOT NULL AUTO_INCREMENT,
  `board_id` int(15) NOT NULL,
  `first_msg_id` int(15) NOT NULL,
  `last_msg_id` int(15) NOT NULL,
  `author_id` int(15) NOT NULL,
  `updater_id` int(15) NOT NULL,
  `title` text NOT NULL,
  `date_posted` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `date_updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `views` int(15) NOT NULL,
  `status` tinyint(1) NOT NULL,
  `type` tinyint(1) NOT NULL COMMENT '0 normal, 1 sticky, 2 global.',
  PRIMARY KEY (`thread_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `forum_boards` (
  `board_id` int(15) NOT NULL AUTO_INCREMENT,
  `parent_id` int(15) NOT NULL,
  `category_id` int(15) NOT NULL,
  `last_msg_id` int(15) NOT NULL,
  `position` tinyint(1) NOT NULL,
  `title` text NOT NULL,
  `description` text NOT NULL,
  `status` tinyint(1) NOT NULL,
  `thread_count` int(15) NOT NULL,
  `reply_count` int(15) NOT NULL,
  PRIMARY KEY (`board_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

这是我的查询:

$query_board_replies = "
                    SELECT
                        m.message_id, m.thread_id,
                        t.thread_id, t.first_msg_id, t.board_id
                    FROM forum_messages AS m
                    LEFT JOIN forum_threads AS t ON t.first_msg_id != m.message_id
                    WHERE t.board_id = ".$board_id."
                    ORDER BY m.message_id";

它不会返回任何错误,但它给了我一个完全错误的计数。只有两个实际回复,但在特定面板中返回的计数为 18。

有什么想法吗?

最佳答案

这应该可以。

$query = "
  SELECT
    COUNT(*)
  FROM
    forum_messages A,
    forum_threads  B
  WHERE
    A.thread_id   = B.thread_id    AND
    A.message_id != B.first_msg_id AND
    B.board_id    = " . mysqli_real_escape_string($dbc, $board_id) . "
";
$rs = mysqli_query($dbc, $query);
list($count) = mysqli_fetch_array($rs);
echo $count;

关于php - 如何计算自定义论坛的留言板中的回复数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17660050/

相关文章:

sql 连接语法

php - 在其他表中使用关系表的 ID

php - 如何使用 PHP 计算多个 MySQL 查询的唯一结果?

php - 如何确保用户不会进入 PHP 中的特定页面?

php - 导出为 CSV 俄语字符时不会显示

sql - 连接条件为 where 子句时使用的连接类型

php - 如何使用 Datamapper 计算 Codeigniter 中查询返回的行数

php - fopen 在普通 PHP 中工作,但在 Drupal 中不起作用

Mysql DB 表行消失

mysql - SQL 多重内连接