I am writing a script for my custom forums that determines if new threads or replies have been posted in a certain board since the user's last visit to that board(board_marks). I have two tables: one that stores threads, another that stores replies. I can easily find if there are any new replies in a board by using a left join. I want to add a bit that finds if there are new threads in that board. How would I do this?
My Tables:
CREATE TABLE IF NOT EXISTS `forum_threads` (
`thread_id` int(15) NOT NULL AUTO_INCREMENT,
`board_id` int(15) NOT NULL,
`author_id` int(15) NOT NULL,
`updater_id` int(15) NOT NULL,
`title` text NOT NULL,
`content` 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_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,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
My Script:
$this->db->select('m.message_id, m.thread_id, m.date_posted, t.thread_id, t.board_id');
$this->db->from('forum_messages AS m');
$this->db->join('forum_threads AS t', 'm.thread_id = t.thread_id', 'left');
$this->db->where('t.board_id', $board_id);
$this->db->where('m.date_posted > "'.$last_mark['date_marked'].'"');
if($query_new_messages = $this->db->get()){
if($query_new_messages->num_rows() > 0){
$contains_new_posts = TRUE;
} else {
$contains_new_posts = FALSE;
}
}
The actual query:
SELECT
m.message_id, m.thread_id, m.date_posted, t.thread_id, t.board_id
FROM (forum_messages AS m)
LEFT JOIN forum_threads AS t ON m.thread_id = t.thread_id
WHERE `t`.`board_id` = '10' AND `m`.`date_posted` > "2014-03-02 06:01:31"
PS: I am doing this in CodeIgniter.