INSERT INTO ..... SELECT FROM

时间:2012-11-28 10:55:27

标签: php codeigniter insert-select

我想将calory作为fruits的第一个值,我无法做到,有人可以帮忙吗?

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

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

5 个答案:

答案 0 :(得分:5)

正确的语法是:

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

在你的情况下,这应该是:

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

(如果“calory”是表“fruits”中列的名称)

答案 1 :(得分:1)

当您使用占位符作为值时(在您的情况下是问号),您需要使用 - > prepare()而不是 - > query()。您的SQL语法也完全错误。 猜测我认为您的查询应该读取类似......

$sql = "INSERT INTO fruits VALUES('', ?, ?, ?) WHERE fruit = ?"; // Create query string.

$sth = $this->db->prepare($sql); // Prepare the query.
$sth->bindValue(1,$a); // Bind question marks to values
$sth->bindValue(2,$b); // (I am assuming that a,b,c,d are in
$sth->bindValue(3,$c); // the correct order...
$sth->bindValue(4,$d);
$sth->execute(); // Execute the query to insert the data.

答案 2 :(得分:0)

您无法在一个查询中混淆INSERT ... SELECTINSERT ... VALUES。只需在SELECT语句中选择其他值作为常量,就可以了:

INSERT INTO fruits
  SELECT calory, ?, ?, ?
  FROM diet
  WHERE fruit = ?

答案 3 :(得分:0)

INSERT INTO fruits SELECT calory, ?, ?, ? FROM diet WHERE fruit = ?

应该这样做......

答案 4 :(得分:0)

你的意思是你需要将select查询的答案放入插入查询中,请尝试这个

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

     ';