2011-12-30 116 views
1

如何在mysql中更新時使用連接?到目前爲止,我有這個...JOIN UPDATE mysql,無法正常工作

$q = $dbc -> prepare("UPDATE items i JOIN accounts a SET i.shrapnel = i.shrapnel-1000, a.gender = a.? WHERE id = ? LIMIT 1"); 
$q -> execute(array($gender, $user['id'])); 

對此我很陌生,我做錯了什麼?

回答

1

這些工作提供了

  • 如果id字段在兩個itemsaccounts
  • ID是兩個表中相同的數據類型

您可以嘗試

$q = $dbc -> prepare("UPDATE items i JOIN accounts a USING (id) SET i.shrapnel = i.shrapnel-1000, a.gender = a.? WHERE i.id = ? LIMIT 1"); 
$q -> execute(array($gender, $user['id'])); 

$q = $dbc -> prepare("UPDATE items i JOIN accounts a ON i.id = a.id SET i.shrapnel = i.shrapnel-1000, a.gender = a.? WHERE i.id = ? LIMIT 1"); 
$q -> execute(array($gender, $user['id'])); 

$q = $dbc -> prepare("UPDATE items i NATURAL JOIN accounts a SET i.shrapnel = i.shrapnel-1000, a.gender = a.? WHERE i.id = ? LIMIT 1"); 
$q -> execute(array($gender, $user['id'])); 
+0

好會嘗試這一點,謝謝。在之前沒有遇到'USING'語法,我猜這是主鍵相同的情況? – cgweb87 2011-12-30 20:20:51

+0

如果id字段在兩個表中並且它們是相同的數據類型,則USING(id)與'i.id = a.id'相同。如果是,那麼'USING(id)'起作用。 – RolandoMySQLDBA 2011-12-30 20:23:29

0

的ID所需要的表識別符。我也會使用「AS」。

$q = $dbc -> prepare("UPDATE items AS i JOIN accounts AS a SET i.shrapnel = i.shrapnel-1000, a.gender = a.? WHERE a.id = ? LIMIT 1"); 
$q -> execute(array($gender, $user['id'])); 
0

可能需要一個連接ON什麼?:

$q = $dbc -> prepare(" 
UPDATE 
    items i JOIN accounts a ON (i.commonField = a.commonField) 
SET 
    i.shrapnel = i.shrapnel-1000 , 
    a.gender = a.? 
WHERE 
    id = ? LIMIT 1"); 
$q -> execute(array($gender, $user['id'])); 

檢查:http://dev.mysql.com/doc/refman/5.0/en/join.html