1

I have 2 tables with different structures.

CREATE TABLE test1
(
    id INTEGER PRIMARY KEY,
    EmpName VARCHAR(50),
    Empid INTEGER
);

CREATE TABLE test2
(
    Empid INTEGER PRIMARY KEY,
    EmpFName VARCHAR(50),   
    EmpLName VARCHAR(50)
);

Is there a way to insert rows from test2 table into test1? If the row exists in test1 it should update the row as well. I think it's possible with Merge statement but it's not available for MySQL. Is there a similar function like this in MySQL?

I've looked into INSERT ... ON DUPLICATE KEY UPDATE but the tables should have the same primary keys.

Kate Lastimosa
  • 169
  • 2
  • 15

2 Answers2

0

I think this can help you.

  1. Create Trigger to detect when insert/update data in your table test2.
  2. Inside Trigger use REPLACE INTO to change data in your table test1.

Please check this link for additional of REPLACE INTO command.

0

Is there a way to insert rows from test2 table into test1? If the row exists in test1 it should update the row as well

UPDATE test1
JOIN test2 USING (Empid)
SET test1.EmpName = CONCAT_WS(' ', EmpFName, EmpLName)

Pay attention - EmpName max length is 50 whereas total length of combined name may be up to 50+1+50=101, so the combined value may be truncated. Increase max length for EmpName.


If you need to perform this operation automatically when the data in test2 is inserted/updated then use AFTER INSERT and AFTER UPDATE triggers, like

CREATE TRIGGER tr
AFTER INSERT -- and the same trigger on AFTER UPDATE event
ON test2
FOR EACH ROW
UPDATE test1 
  SET EmpName = CONCAT_WS(' ', NEW.EmpFName, NEW.EmpLName)
  WHERE test1.Empid = NEW.Empid;
Akina
  • 39,301
  • 5
  • 14
  • 25