gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:36:32 25 4
gpt4 key购买 nike

我正在为我的自定义论坛编写一个脚本,用于确定自用户上次访问该版 block (board_marks)以来是否在某个版 block 中发布了新主题或回复。我有两个表:一个存储线程,另一个存储回复。我可以使用左连接轻松查找论坛中是否有任何新回复。我想添加一些内容来查找该板上是否有新线程。我该怎么做?

我的 table :

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 中执行此操作。

最佳答案

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")

但是,您应该对此进行基准测试。这个解决方案可能不是很优化。您应该对执行两项快速查询(一项针对帖子,一项针对线程)与执行一项可能较慢的查询进行基准测试。

关于mysql - 如何将这两个查询合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com