关于php:如何从另一个表更新mysql pdo中的字段

how to update a field in mysql pdo from another table

本问题已经有最佳答案,请猛点这里访问。

这不是一个重复的问题。 上一个问题与PDO无关。 我在mysql中有两个表:

1
2
3
4
5
6
7
8
9
10
11
12
USERS
-------------------------------------
employeeid  | name | saving | salary
-------------------------------------
12           | Bob | 100     | 1000
23           | Joe | 50      | 800

USERS table
employeeid
name
saving
salary

和:

1
2
3
4
5
6
7
8
9
10
EMPLOYEE
-----------------------------------
id   |  managerid  | workerid
-----------------------------------
1    |    12       |  23

EMPLOYEE table
id
managerid FOREIGN KEY
workerid FOREIGN KEY

1-(经理和工人都是雇员)为了更新工人的保存字段(比如+ 10美元),现场工资需要更新 - $ 10

2-输入变量来自PHP格式为name,因此逻辑流程为:

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

所以sql语句可以分别写成:

1
2
3
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格式)。
上面的msql PDO格式(用PHP):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$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);

任何帮助,将不胜感激!


1
2
3
4
5
6
7
$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);