[英]Update a third table by comparing values of two tables using triggers
Hii i
I have three tables (Table1, Table2, Table3).All the three tables have same column names(Company, License_count). 我有三个表(Table1,Table2,Table3)。所有三个表都具有相同的列名(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.
当table2中发生更新时,触发器将比较table2和table1的值,并将差异插入表3中。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.