我希望MySQL比较表中2列的值。如果两个值相同,则必须在另一个表上执行UPDATE语句。这些是我的2个表:
表:员工
EMPLOYEE_ID | NAME | CREDIT
---------------------------
1 | John | 5
2 | Bill | 10
3 | Mark | 7
表:奖金
BONUS_ID | EMPLOYEE_ID | A | B | AMOUNT
---------------------------------------
1 | 1 | x | x | 6
2 | 2 | x | y | 19
3 | 2 | y | x | 4
4 | 3 | y | y | 12
5 | 3 | x | x | 15
如果在奖金表中,A列的值等于B列的值,则必须将该行的“金额”值添加到employees-table中的雇员信用。在SQL中,它将是这样的:
SELECT * FROM bonuses WHERE A = B;
..之后:
UPDATE employees SET credit = credit + bonuses.amount
- >例如:
在“奖金”表格中,第一行的值A是euqal到值B.这意味着拥有EMPLOYEE_ID 1(John)的员工必须在其信用额度上添加6。第四行也是如此,其中值A等于值B.在这种情况下,具有EMPLOYEE_ID 3(标记)的员工必须在其信用额度中添加12。
有谁知道怎么做?谢谢!
答案 0 :(得分:1)
您可以使用多表更新来连接表:
UPDATE EMPLOYEES JOIN BONUSES USING (EMPLOYEE_ID)
SET EMPLOYEES.CREDIT = EMPLOYEES.CREDIT + BONUSES.AMOUNT
WHERE BONUSES.A = BONUSES.B
但是,您可能希望考虑是否可以在trigger中更好地实现此逻辑:
CREATE TRIGGER foo AFTER INSERT ON BONUSES FOR EACH ROW
IF NEW.A = NEW.B THEN
UPDATE EMPLOYEES
SET CREDIT = CREDIT + NEW.AMOUNT
WHERE EMPLOYEE_ID = NEW.EMPLOYEE_ID
END IF
;
答案 1 :(得分:1)
尝试此查询
update EMPLOYEE E
inner join BONUSES B on
E.EMPLOYEE_ID = B.EMPLOYEE_ID AND B.A = B.B
set E.CREDIT = E.CREDIT + B.AMOUNT;