【发布时间】:2014-08-08 14:16:49
【问题描述】:
在我的数据库中,我有 3 个表。
笑话:
CREATE TABLE IF NOT EXISTS `jokes` (
`joke_id` int(11) NOT NULL AUTO_INCREMENT,
`joke` varchar(1024) NOT NULL,
`category_id` int(11) NOT NULL,
`vote` int(255) NOT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
类别:
CREATE TABLE IF NOT EXISTS `category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(51) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
最后,评论:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`comment` text NOT NULL,
`joke_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
我需要将所有三个表连接在一起,以获取笑话的类别名称、笑话本身以及与该特定笑话_id 相关的唯一 cmets。
目前我只能加入两个 joke_id = 1 的表。这将返回那个笑话的 cmets。
这个函数存储在我的读控制器里,名字叫笑话:
public function joke($joke_id = FALSE)
{
if ($joke_id === FALSE) redirect('main'); //go to default controller
$data['results'] = $this->comments_m->getComments($joke_id, $this->uri->segment(2));
$this->load->view('template/header');
$this->load->view('template/sidebar');
$this->load->view('content/read', $data);
$this->load->view('template/footer');
}
模型 (cmets_m) 有一个名为 getComments 的函数,它获取与 joke_id = 1 相关的 cmets:
//gets the comments
function getComments (){
//joke id should grab the id of the joke which was commented on
$joke_id = 1;
$query = $this->db->query("SELECT jokes.*, comments.* FROM jokes LEFT OUTER JOIN comments ON jokes.joke_id = comments.joke_id WHERE jokes.joke_id = '$joke_id'");
return $query->result();
}
我需要 getComments 函数中的 SQL 查询,该查询获取类别名称、笑话、joke_id、comment 和 comment_id。如何更改我的查询以返回我需要的信息?
【问题讨论】:
标签: php mysql sql codeigniter join