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.
After some googling and experimenting with the answers here, I came up with this solution. It turns out that MySQL supports
REPLACE INTO...and...ON DUPLICATE KEY UPDATE. So my query would be like this:or,
If a row exists on
stock_total, the first query will DELETE then INSERT the new row,and the second query will UPDATE the existing row.
Both query will only work if the table has a primary key or unique index:
Documentation: