IF condition for INSERT AND UPDATE in SQL

user13053989 :

I have a table called EMPLOYEE and created a new table EMPLOYEE_SALARY_CHANGE (to track employee salary changes)

here is EMPLOYEE table

ID | Employee_Salary | Active
1        500 -> 700       1
2          600            1
3         2100            1

500->700 means the employee_salary is changed from 500 to 700.

Here is EMPLOYEE_SALARY_CHANGE table

ID | Employee_Salary | Active
1          500            0
1          700            1
2          600            1
3         2100            1

when employee salary is changed from 500 to 700, I have to insert a new row in EMPLOYEE_SALARY_CHANGE

and update existing one's active to 0.

IF (EMPLOYEE.EMPLOYEE_SALARY != EMPLOYEE_SALARY_CHANGE.EMPLOYEE_SALARY, 
INSERT EMPLOYEE_SALARY_CHANGE INTO (EMPLOYEE.ID,EMPLOYEE.EMPLOYEE_SALARY,1) UNION 
UPDATE EMPLOYEE_SALARY_CHANGE SET ACTIVE = 0 WHERE EMPLOYEE.EMPLOYEE_SALARY = EMPLOYEE_SALARY_CHANGE.EMPLOYEE_SALARY))

but there is something wrong. Do you think it is better to use php or can be handled in sql?

P.Salmon :

Normally you would use a trigger to handle the upsert . For example

drop table if exists employee,employee_salary_change;
create table employee
(ID  int, Employee_Salary int, Active int);
insert into employee values
(1      ,    500   ,     1),
(2      ,    600   ,     1),
(3      ,    2100  ,     1);

create table EMPLOYEE_SALARY_CHANGE(
ID int, Employee_Salary int, Active int);
insert into employee_salary_change values
(1   ,       500   ,         1),
(2   ,       600   ,         1),
(3   ,      2100   ,         1);

drop trigger if exists t;
delimiter $$
create trigger t after update on employee
for each row 
begin
    update employee_salary_change
        set active = 0 where id = new.id;
    insert into employee_salary_change values (new.id,new.employee_salary,new.active);
end $$

delimiter ;
update employee 
    set employee_salary = 700 where id = 1;
select * from employee;
+------+-----------------+--------+
| ID   | Employee_Salary | Active |
+------+-----------------+--------+
|    1 |             700 |      1 |
|    2 |             600 |      1 |
|    3 |            2100 |      1 |
+------+-----------------+--------+

select * from employee_salary_change;

+------+-----------------+--------+
| ID   | Employee_Salary | Active |
+------+-----------------+--------+
|    1 |             500 |      0 |
|    2 |             600 |      1 |
|    3 |            2100 |      1 |
|    1 |             700 |      1 |
+------+-----------------+--------+

I assume your employee_salary_change table is simplified for the purpose of the question so I haven't tested to see if same salary already exists.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=346824&siteId=1
Recommended