2017-03-01 142 views
1

這不是重複的問題。前面的問題與PDO無關。我在mysql的兩個表:如何從另一個表中更新mysql pdo中的字段

USERS 
------------------------------------- 
employeeid | name | saving | salary 
------------------------------------- 
12   | Bob | 100  | 1000 
23   | Joe | 50  | 800 

USERS table 
employeeid 
name 
saving 
salary 

和:

EMPLOYEE 
----------------------------------- 
id | managerid | workerid 
----------------------------------- 
1 | 12  | 23 

EMPLOYEE table 
id 
managerid FOREIGN KEY 
workerid FOREIGN KEY 

1-(既經理和工人都是員工),以更新保存領域的workerid(以+ 10 $說)字段薪水需要由被更新 - 10 $

2-輸入變量來自PHP形式name,所以邏輯流程是:

name > find employeeid (id) from USERS > find managerid (id2) from EMPLOYEE > find employeeid (id3) from USERS > update saving and salary 

所以單獨的SQL語句可以寫成:

id = SELECT employeeid FROM USERS WHERE name = $name; //find id of employee in USERS 
id2 = SELECT managerid FROM EMPLOYEE WHERE workerid = id; //find id of worker in EMPLOYEE 
UPDATE USERS SET saving = saving + 10, salary = salary -10 WHERE employeeid = id2; 

是否有可能在一個做這3個報表(以PDO格式)。以上(與PHP) mSQL的PDO格式:

$sql = "SELECT employeeid FROM USERS WHERE name=:namepara"; 
$sttm = prepare($sql); 
$sttm->execute(array(":namepara"=>$name)); 
$row=$sttm->fetch(PDO::FETCH_ASSOC); 

$sql2 = "SELECT managerid FROM EMPOYEE WHERE workerid=:idpara"; 
$sttm2 = prepare($sql2); 
$sttm2->execute(array(":idpara"=>$row['employeeid'])); 
$row2=$sttm2->fetch(PDO::FETCH_ASSOC); 

$sql3 = "UPDATE USERS SET saving = saving + 10, salary = salary - 10 WHERE 
    employeeid=:id2para"; 
$sttm3 = prepare($sql3); 
$sttm3->execute(array(":id2para"=>$row2['managerid'])); 
$row3=$sttm3->fetch(PDO::FETCH_ASSOC); 

任何幫助,將不勝感激!

+0

您的查詢應該是這樣的'UPDATE USERS INNER JOIN EMPLOYEE ON USERS.employeeid = EMPLOYEE.managerid SET 儲蓄=節能+ 10 ,工資=工資 - 10 WHERE USERS.name ='name'' –

+0

謝謝,您提供的解決方案不是PDO。我可以做多個INNER JOIN,但是使用PDO它有點棘手,或者我不太瞭解它。 – Tempo

回答

2
$sql = "UPDATE USERS JOIN EMPLOYEE ON USERS.employeeid = EMPLOYEE.managerid 
     SET Saving = saving +10, salary = salary - 10 
     WHERE USERS.name = :namepara"; 

$sttm = prepare($sql); 
$sttm->execute(array(":namepara"=>$name)); 
$row=$sttm->fetch(PDO::FETCH_ASSOC); 
+0

嗨Naincy。非常感謝您的及時回覆。我試過你的代碼,我得到這個錯誤:SQLSTATE [HY000]:一般錯誤:1093你不能指定目標表'用戶'在FROM子句更新 – Tempo

+0

我跟隨在http://stackoverflow.com/questions/ 45494/mysql-error-1093 -cant-specified-target-table-for-update-in-from-clause但仍然得到上述相同的錯誤。任何建議? – Tempo

+0

@Tempo修改我的查詢...你能檢查更新的答案 – Naincy

相關問題