简体   繁体   中英

Update a third table by comparing values of two tables using triggers

Hii

I have three tables (Table1, Table2, Table3).All the three tables have same column names(Company, License_count). when an update will happen in table2, trigger will compare the values of table2 & table1 and insert the difference into table three. I have to do this only for single row.

Can anyone help?

Alright, I got it.

drop trigger if exists table1and2difference;
CREATE TRIGGER table1and2difference
AFTER UPDATE ON Table2
FOR EACH ROW
  INSERT INTO Table3(Company, License_count)values
    (new.Company, (SELECT (SUM(License_count1) - License_count2) as License_count FROM
                   (SELECT Company as company1, License_count as License_count1 FROM 
                           Table1 WHERE Company=new.Company) AS t1
                   INNER JOIN
                   (SELECT Company as company2, License_count as License_count2 FROM
                           Table2 WHERE Company=new.Company) As t2
                   On company1=company2));

For reference, these are the values I used to test the trigger.

create table Table1(
Company VARCHAR(100) NOT NULL,
License_count INT NOT NULL);

insert into Table1(Company,License_count)values('Test_company',10);

create table Table2(
Company VARCHAR(100) NOT NULL,
License_count INT NOT NULL);

insert into Table2(Company,License_count)values('Test_company',8);

create table Table3(
Company VARCHAR(100) NOT NULL,
License_count INT NOT NULL);

drop trigger if exists table1and2difference;
CREATE TRIGGER table1and2difference
AFTER UPDATE ON Table2
FOR EACH ROW
     INSERT INTO Table3(Company, License_count)values
         (new.Company, (SELECT (SUM(License_count1) - License_count2) as License_count FROM
                            (SELECT Company as company1, License_count as License_count1 FROM Table1 WHERE Company=new.Company) AS t1
                            INNER JOIN
                            (SELECT Company as company2, License_count as License_count2 FROM Table2 WHERE Company=new.Company) As t2
                            On company1=company2));

update Table2 set License_count=7;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM