3

我想把它calory作为第一个值fruits,我做不到,有人可以帮忙吗?

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

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

5 回答 5

6

正确的语法是:

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

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

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

(如果“卡路里”是“水果”表中列的名称)

于 2012-11-28T11:02:53.960 回答
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.
于 2012-11-28T11:03:59.087 回答
0

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

INSERT INTO fruits
  SELECT calory, ?, ?, ?
  FROM diet
  WHERE fruit = ?
于 2012-11-28T10:58:28.213 回答
0

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

应该这样做...

于 2012-11-28T10:58:35.017 回答
0

您的意思是您需要将选择查询的答案放入插入查询中,请试试这个

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

     ';
于 2012-11-28T11:00:00.553 回答