Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put multiple updates in a trigger?

I hope you can help me here. I am using MySQL + PhpMyAdmin and I have 2 tables in this problem.

Table 1: Accounts - id, account_name, website, etc. etc...
Table 2: Domains - id, domain_name, account_name

and I Inserted these queries into 2 triggers.

Before Update
update domains, accounts
set domains.account_name = NULL
where accounts.website != domains.domain_name

After Update
update domains, accounts
set domains.account_name = accounts.account_name
where domains.domain_name = main_accounts.website

With these, when I update something in the accounts table, it will automatically remove the account_name from domains table and put new account_name if a certain account is updated.

Images below will show example.
Tables not yet updated:
----------
Accounts Table
enter image description here

Domains Table
enter image description here ----------
----------
Updated View.
----------
----------
Accounts Table
enter image description here

Domains Table
enter image description here

So, on the second account table image, I have changed the domain and automatically, the domains table has been updated. I would want to make only 1 trigger that will contain those 2 update queries. I don't know if it's possible because after I complete this, I may also need to know how to update multiple different tables from 1 trigger. The reason why I ask is because I need to assign the account name for each sub-tables that are in use. Example, the main table is the accounts table and the sub tables that needs to be updated are:
domains.account_name
ip_address.account_name
phones.account_name
payments.account_name

So, I don't know if it's even possible to update those sub-tables under column "account_name" when the main table "accounts" is updated.

Thank you. I hope my question is clear. :D :D

like image 913
Mark Juni Avatar asked Mar 16 '23 07:03

Mark Juni


1 Answers

You can group multiple statements into a trigger with BEGIN and END.

Example:

DELIMITER $$

CREATE TRIGGER my_trigger BEFORE INSERT ON accounts
FOR EACH ROW
BEGIN
    -- Statement one
    UPDATE domains
    SET domains.account_name = accounts.account_name
    WHERE domains.domain_name = main_accounts.website;
    -- Statement two
    UPDATE another_table
    SET another_table.column_name = accounts.account_name
    WHERE another_table.domain_name = accounts.some_column;
    -- More UPDATE statements
END$$
like image 180
Lloyd Banks Avatar answered Mar 19 '23 10:03

Lloyd Banks