【问题标题】:INSERT INTO.....SELECT FROM插入到.....选择从
【发布时间】:2012-11-28 10:55:26
【问题描述】:

我想把calory 作为fruits 的第一个值,我做不到,谁能帮忙?

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

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

【问题讨论】:

    标签: php codeigniter insert-select


    【解决方案1】:

    正确的语法是:

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

    在你的情况下应该是:

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

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

    【讨论】:

      【解决方案2】:

      当您对值使用占位符时,(在您的情况下是问号)您需要使用 ->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.
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

          这个

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

          应该这样做......

          【讨论】:

            【解决方案5】:

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

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-03-19
              • 1970-01-01
              • 2016-07-23
              • 1970-01-01
              • 2013-05-26
              相关资源
              最近更新 更多