使用SQL语句将表行ID的值赋给另一个ID


Assigning the value of a table row ID with another ID using an SQL statement

所以在我的数据库我有两个表。笑话和评论。我希望能够将评论的post_id分配给笑话的joke_id,因此它将分配和检索与该笑话相关的评论。我的问题是,我不擅长写SQL语句,也不知道如何连接两个表来实现这一点。

我的笑话表是这样的:

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

目前,我通过分配$post_id ="1"来抓取数据,但我想将其更改为$post_id = $joke_id(与笑话id在同一函数中,但我不知道如何做到这一点)。

我正在使用一个MVC与codeigniter如果有任何帮助。

在我的控制器中,我有一个名为comments的php文件,它有一个名为insertComment的函数,看起来像这样:

public function insertComment(){
//extracts the data from the ajax
extract($_POST);
if($_POST['act'] == 'add-com'){
    //assigned the db rows with the actual data which was inputted
    $data = array(
        'name' => htmlentities($name),
        'comment' => htmlentities($comment),
        //id_post should correlate to the joke_id
        'id_post' => $id_post = "1"
        );

    $this->comments_m->insertComment($data);
}

和我的insertComment函数,在comment_m函数的模型中是这样的:

function insertComment (){
extract($_POST);
if($_POST['act'] == 'add-com'){
    $data = array(
        'name' => htmlentities($name),
        'comment' => htmlentities($comment),
        'id_post' => $id_post = "1"
    );
    if(strlen($data['name']) <= '1'){
        $data['name'] = 'Guest';
    }
    $this->db->insert('comments', $data);
}
}

最后,这将是一个很大的帮助,如果有人可以帮助一个SQL语句连接两个表在一起,其中joke_id具有相同的值作为评论的post_id,这将使它唯一的笑话。

谢谢

连接这两个表的SQL是-

SELECT `jokes`.*, `comments`.*
FROM `jokes`
LEFT OUTER JOIN `comments`
ON `jokes`.`joke_id` = `comments`.`joke_id`

这将返回每个笑话的所有评论。然后,您可以通过添加WHERE子句来筛选或限制—

WHERE `jokes`.`joke_id` = 1