[英]MySQL - Combine SELECT and UPDATE?
I would like MySQL to compare the values of 2 columns in a table. 我希望MySQL比较表中2列的值。 If both values are the same, an UPDATE-statement must be executed on another table.
如果两个值相同,则必须在另一个表上执行UPDATE语句。 These are my 2 tables:
这些是我的2个表格:
TABLE : EMPLOYEES 表 :员工
EMPLOYEE_ID | NAME | CREDIT
---------------------------
1 | John | 5
2 | Bill | 10
3 | Mark | 7
TABLE : BONUSES 表 :奖金
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
If in the bonuses-table the value of column A is equal to the value of column B, the "amount" value of that row must be added to the employees credit in the employees-table. 如果在奖金表中,列A的值等于列B的值,则必须将该行的“金额”值添加到employees-table中的雇员信用。 In SQL, it would be something like this:
在SQL中,它将是这样的:
SELECT * FROM bonuses WHERE A = B;
..and after that: ..在那之后:
UPDATE employees SET credit = credit + bonuses.amount
-> For example: - >例如:
In the "bonuses" table, the first row value A is euqal to value B. That means that the employee with EMPLOYEE_ID 1 (John) must have added 6 to their credit. 在“奖金”表中,第一行值A是euqal到值B.这意味着具有EMPLOYEE_ID 1(John)的员工必须在其信用额度中添加6。 The same goes for the 4th row where value A is equal to value B. In that case, the employee with EMPLOYEE_ID 3 (Mark) must have added 12 to their credit.
第四行也是如此,其中值A等于值B.在这种情况下,具有EMPLOYEE_ID 3(标记)的员工必须在其信用额度中添加12。
Does anyone know how to do this? 有谁知道如何做到这一点? Thanks!
谢谢!
You can use a multiple-table update to join the tables: 您可以使用多表更新来连接表:
UPDATE EMPLOYEES JOIN BONUSES USING (EMPLOYEE_ID)
SET EMPLOYEES.CREDIT = EMPLOYEES.CREDIT + BONUSES.AMOUNT
WHERE BONUSES.A = BONUSES.B
However, you may wish to consider whether this logic would be better implemented in a 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
;
Try this query 试试这个查询
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.