mySQL: UPSERT (INSERT OR UPDATE) between 2 tables

In order to INSERT new rows or UPDATE if the rows exist you can use the following SQL:

Step 1:
INSERT INTO PRODUCT_T (ID, NAME, DESCR)

SELECT T2.ID, T2.NAME, T2.DESCR FROM
(IMP_PRODUCT_T T2 LEFT OUTER JOIN PRODUCT_T T1 ON T2.ID = T1.ID)
WHERE T1.ID IS NULL;

Step 2:
UPDATE PRODUCT_T T1
INNER JOIN IMP_PRODUCT_T T2 ON T1.ID = T2.ID
SET T1.NAME = T2.NAME, T1.DESCR = T2.DESCR


Note: It has poor efficiency but it is standards compliant!!!

No comments:

Post a Comment