If you want to update Table2
as needed, then you need to update existing rows first, and then insert new rows from Table1
:
You can update the device using JOIN
:
UPDATE Table2 t2 JOIN (SELECT nm, SUM(unit) unit FROM ( SELECT * FROM Table1 t1 UNION ALL SELECT * FROM Table2 t2 ) tbl GROUP BY nm ) tbl1 ON t2.nm = tbl1.nm SET t2.unit = tbl1.unit;
Then you can add rows from table 1 that are not in table 2 (e.g. nm=AYU
)
INSERT INTO Table2 SELECT t1.`no`, t1.`nm`, t1.`unit` FROM Table1 t1 LEFT JOIN Table2 t2 ON t1.nm = t2.nm WHERE t2.nm IS NULL;
Output:
SELECT * FROM Table2; | NO | NM | UNIT | |----|-----|------| | 1 | ABC | 50 | | 2 | ACX | 40 | | 3 | AYU | 30 |
Remember to update the table first. Otherwise, it will duplicate units.
source share