我想把calory
作爲fruits
的第一個值,我做不到,任何人都可以幫忙嗎?INSERT INTO .....從
$sql = 'INSERT INTO fruits VALUES('', ?, ?, ?)'
SELECT calory
FROM diet
WHERE fruit = ?
';
$this->db->query($sql, array($a, $b, $c, $d));
我想把calory
作爲fruits
的第一個值,我做不到,任何人都可以幫忙嗎?INSERT INTO .....從
$sql = 'INSERT INTO fruits VALUES('', ?, ?, ?)'
SELECT calory
FROM diet
WHERE fruit = ?
';
$this->db->query($sql, array($a, $b, $c, $d));
正確的語法是:
INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2"
在你的情況下,這應該是:
INSERT INTO fruits (calory)
SELECT calory
FROM diet
WHERE fruit = ?
(如果「卡路里」是表中的「果實」的列名)
在一個查詢中不能混合使用INSERT ... SELECT
和INSERT ... VALUES
。只需在您的SELECT
聲明選擇其他數值作爲常數,你會被罰款:
INSERT INTO fruits
SELECT calory, ?, ?, ?
FROM diet
WHERE fruit = ?
這
INSERT INTO fruits SELECT calory, ?, ?, ? FROM diet WHERE fruit = ?
應該這樣做......
你的意思是,你需要把選擇查詢回答插入查詢,請嘗試此操作
$sql = 'INSERT INTO fruits VALUES('(SELECT calory
FROM diet
WHERE fruit = ?)', ?, ?, ?)'
';
當您使用佔位符值(在你的情況下是問號)你需要使用 - > 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.
其他變量? – NestedWeb