如何将这两个查询合并为一个?

时间:2014-03-02 06:16:57

标签: mysql left-join

我正在为我的自定义论坛编写一个脚本,用于确定自用户上次访问该板(board_marks)以来是否已在某个板上发布新线程或回复。我有两个表:一个存储线程,另一个存储回复。通过使用左连接,我可以很容易地找到板中是否有任何新的回复。我想添加一点,找出该板中是否有新线程。我该怎么做?

我的表格:

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;

我的剧本:

$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;

    }

 }

实际查询:

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:我在CodeIgniter中这样做。

1 个答案:

答案 0 :(得分:0)

OR条件会为您提供所需的数据:

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" 
         OR `t`.`date_posted` > "2014-03-02 06:01:31")

然而,你应该对此进行基准测试。该解决方案可能不是非常优化。你应该做两个快速查询的基准测试 - 一个用于帖子,一个用于线程 - 而不是做一个可能较慢的查询。