2011-01-05 145 views
0

斐伊川更新使用触发器

我有三个表(表1,表2,表3)。所有这三个表具有相同的列名(公司,LICENSE_COUNT)比较两个表的值的第三个表。当表2中发生更新时,触发器将比较table2 & table1的值并将差异插入到表3中。我必须这样做只为单行。

任何人都可以帮忙吗?

回答

0

好的,我明白了。

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)); 

作为参考,这些是我用来测试触发器的值。

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; 
+0

感谢您的回复,我已经尝试过您的脚本,但它没有给出我想要的输出,可能是减法过程没有在触发器中工作。请检查并更新 – user563523 2011-01-05 11:33:10

+0

抱歉编辑中的延迟。我不得不在我的笔记本电脑上重新安装MySQL。 – Holtorf 2011-01-06 08:58:27