Sample Header Ad - 728x90

Creating a Trigger in MySQL that has a JOIN

3 votes
1 answer
560 views
**PROBLEM:** I'm trying to create a TRIGGER that will copy records from 2 different tables (**users**, **addresses**) in database A to a single table (**users**) in database B. Basically, I'm trying to consolidate data into a single table in a different DB. I have the following TRIGGER
CREATE TRIGGER Copy db1_user to db2_users 
AFTER INSERT ON user
FOR EACH ROW 
BEGIN 
    INSERT INTO database2.users(user_id, user_email, user_firstname, user_lastname) 
        VALUES (NEW.user_id, NEW.email, NEW.first_name, NEW.last_name);
END
The above works fine, where I bend my brain is getting the other chunk of data from the address table. I've created a diagram of what I'm trying to achieve, hopefully it makes sense. Oh, it also needs to make sure that the **user_id** doesn't already exist in the target table, which it shouldn't as the **user_id** field in the source table is AUTO INCREMENT. Diagram of TRIGGER My other question is, given the 2 source tables get written to at slightly different times, I'm not sure where to fire this TRIGGER? If I fire it on AFTER INSERT on table (users) will table (addresses) have been written to yet? Not sure - not my code (it's a WordPress application I'm drilling into), so any advice as to where to keep this TRIGGER would be great. Suggestions or assistance would be greatly appreciated.
Asked by Tony Stephens (33 rep)
Jan 16, 2024, 02:59 AM
Last activity: Jan 17, 2024, 11:20 AM