INSERT INTO.....SELECT FROM

NestedWeb picture NestedWeb · Nov 28, 2012 · Viewed 15.2k times · Source

i want to put calory as the first value of fruits, i couldn't do it, can anyone help?

   $sql = 'INSERT INTO fruits VALUES('', ?, ?, ?)'
          SELECT calory
          FROM diet
          WHERE fruit = ?
         ';

   $this->db->query($sql, array($a, $b, $c, $d));

Answer

Hugo picture Hugo · Nov 28, 2012

The correct syntax is :

INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2"

in your case this should be :

INSERT INTO fruits (calory)
SELECT calory
FROM diet
WHERE fruit = ?

(if "calory" is the name of the column in the table "fruits")