我正在开发一个使用PHP和MySQL的自定义论坛。在这种情况下,我有三个主表:板,线程和消息。我想计算一块板子里的消息数量。 threads表有一个名为“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个。
有什么想法吗?
答案 0 :(得分:0)
这应该这样做。
$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;