DEV Community 👩‍💻👨‍💻

Kirinyet Brian
Kirinyet Brian

Posted on

mysql triggers

Hello. I need 2 small triggers written. Now before you tell me I could just run a join in my select query to get what I'm looking for, other limitations not in my control will not allow me to do so. So, I need to get creative...

Trigger 1:
On insert into the Contact table, I need a trigger to copy the ExternalId from the Company related to a new contact record to the CompanyExtId field on the Contact.

On update of an existing record in the Contact table, I need a trigger to copy the ExternalId from the (potentially updated) Company related to the updated contact record to the CompanyExtId field on the Contact.

Here is an example schema:
create TABLE Company (Id int auto_increment, Name char(20), ExternalId char(20), PRIMARY KEY (Id));
create TABLE Contact (Id int auto_increment, FirstName char(20), LastName char(20), CompanyExtId char(20), PRIMARY KEY (Id));

Top comments (0)

All DEV content is created by the community!

Hey, if you're landing here for the first time, you should know that this website is a global community of folks who blog about their experiences to help folks like you out.

Sign up now if you're curious. It's free!