触发更新其他表与计数

时间:2017-01-05 18:30:15

标签: mysql join triggers group-by

我有三个表:联系帐户 account_contact 。 account_contact具有联系人和帐户之间的关系。

帐户表格中,我有 account_contacts 字段,其中包含每个帐户的联系人计数。我可以运行一个更新此值的sql,但我想在每次创建或更新联系表时更新它。

这是更新sql:

update account a 
  left join (
    select ac.account_id as a_id, count(c.id) as contacts
    from account_contact ac
    inner join contact c
    on ac.contact_id = c.id
    where c.deleted = 0
    group by ac.account_id
    ) as n 
    ON a.id = n.a_id
    SET a.account_contacts = n.contacts

这是我尝试过的代码:

CREATE TRIGGER `contact_new` AFTER INSERT ON `contact`
 FOR EACH ROW update account a set a.account_contacts = a.account_contacts + 1 
where a.id = (select ac.account_id from account_contact ac where ac.contact_id = NEW.id)

我在stackoverflow中找到的关于触发器的答案只有两个表。

1 个答案:

答案 0 :(得分:0)

好的,完成了!这是代码,它与更新没有太大区别。

CREATE TRIGGER `contact_new` AFTER INSERT ON `contact`
 FOR EACH ROW update account a 
  left join (
    select ac.account_id as a_id
    from account_contact ac
    inner join contact c
    on ac.contact_id = c.id
    where ac.contact_id = NEW.id
    ) as n 
    ON a.id = n.a_id
    SET a.account_contacts = a.account_contacts + 1