I have 2 tables:
stock:
pid name qty
--- ---- ---
1 aaaa 2
2 bbbb 3
1 aaaa 5
3 cccc 1
2 bbbb 2
stock_total:
pid name total_qty
--- ---- ---------
I can insert rows from stock
table with the total qty to stock_total
using this query
INSERT INTO stock_total (pid, name, total_qty)
SELECT pid, name, SUM(qty)
FROM stock
GROUP BY pid, name
The problem is, I will run the SQL above via cron job. So on the next execution, the SQL should UPDATE existing product and INSERT non-exist products.
It would be very inefficient if I loop over the SELECT results, check each row if exists in stock_total
and do the INSERT or UPDATE.
Is there any simpler way for achieving this? perhaps by modifying the SQL above. Thanks.