How to insert data into a child table in mysql

社会主义新天地 提交于 2019-12-12 04:13:11

问题


I have 2 tables, an articles and a summaries table.

The summaries table is a child of the articles table and I would like to add data into the summaries table through the articles table.

The sql for the summaries table is as follows:

  CREATE TABLE summaries(
   summary_id INT NOT NULL AUTO_INCREMENT,
   article_id INT,
   summary TEXT,
   PRIMARY KEY(summary_id),
   FOREIGN KEY(article_id) REFERENCES articles(article_id)
  )ENGINE=INNODB;

How do I add a summary into the summaries table and have the article_id equal to the article_id in my articles table?

Here is how I'm saving my data to articles table:

 $sql = "INSERT INTO articles  (url, domain, favicon, title) VALUES ( '$url','$domain','$favicon','$title')";
    if (mysql_query($sql)){
        $s = "SELECT max(article_id) from articles"; 
        $object1 = mysql_query($s);
    }

here is what I'm trying to do:

       $large_summary = $article_array['summary'];
       foreach ($large_summary as $summary){
          // $summary_sql = "INSERT INTO summaries SET `summary`=(SELECT `sum`.`summary` FROM summaries as sum, articles as art WHERE art.article_id=sum.article_id AND art.article_id=$object1 -> article_id)";
        $summary_sql = "INSERT INTO `summaries` (summary,article_id) VALUES ('$summary' , ('SELECT article_id FROM articles WHERE article.article_id=summary.article_id AND article.article_id = $object1 -> article_id' ))";
        echo $summary_sql;
        $summary_sql_query = mysql_query($summary_sql);

    if(!mysql_query($sql2)){
      die('Error: ' . mysql_error());
    }
        echo "$summary <br>";
    }

I'm looping through the large_summary array to obtain an individual summary which I want to save to the database via the article it is for


回答1:


INSERT INTO summaries SET `summary`=
(SELECT `art`.`summary` FROM summaries as sum, articles as art WHERE
art.article_id=sum.article_id AND art.article_id=123)

Here '123' is a sample article_id i am passing. You have to pass your real article_id



回答2:


try that:

INSERT INTO `summaries` (summary,article_id)
    VALUES ($yoursummryVar , (SELECT article_id 
                              FROM articles
                              WHERE ........)
    )


来源:https://stackoverflow.com/questions/22559796/how-to-insert-data-into-a-child-table-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!