问题
I'm still new and some of the right coding practices escape me. Documentation on this particular situation is weak, so I would like to get some advice/suggestions from you experts :) on the following.
I have an API that allows users to update 2 tables in one call. One is a SUMMARY table and the other is a DETAIL table with an FK to the SUMMARY table.
What I have my code doing is I do an UPSERT (insert/update) to the SUMMARY table, grab the insert_id
and then delete the records from the DETAIL table, then insert the ones I need (referencing SUMMARY with the fk of course).
However, in the instance that there are no changes to SUMMARY data - insert_id
returns 0
. This seems expected as no row was updated/inserted.
So here is my question:
Should I be doing a full read of the tables and comparing data prior to this update/delete/insert attempt? Or is there another nifty way of grabbing the id
of the SUMMARY that was a duplicate of the UPSERT attempt? I feel that my users will 'almost' ALWAYS be changing the SUMMARY and DETAIL data when using this API.
What is the correct coding practice here? Is the extra read worth it every time? Or should I read only if insert_id = 0
?
Thoughts? My biggest problem is that I don't know what the magnitude difference of a read vs a write is here - especially since I don't believe the API will be called much without having changed values.
Again my options are:
- Read db and compare to see if there is a diff
- Insert/Update accordingly
- Attempt Insert/update.
- if (insert_id = 0) then read db to get summary id for details table
- copmlete process
- Attempt Insert/Update
- use ?something? to get id of summary of record that was duplicate (and prevented insert/update)
- use the id to complete steps.
回答1:
If the id you need is an auto_increment field, option 4 (do everything inside DB with 1 execute action) 100% of the time. This is the general SQL structure you need:
Insert into summary (primaryKey, fieldA, fieldB) values (NULL, valueA, valueB) on duplicate key update primaryKey=LAST_INSERT_ID(primaryKey), fieldA = fieldA, fieldB=fieldB;
If you then do SELECT LAST_INSERT_ID()
it'll give you either the successful inserted id or ,if duplicate, the duplicate entrie's id. So do something like:
delete from detail where summary_id = LAST_INSERT_ID();
回答2:
At the companies I've worked for, option 1 is usually the one I've seen used if you're wanting to compare record by record. This can be implemented either in a stored proc or in the code itself. Depends on the context of what "same" means. If it's raw values, then sql is probably the easiest. If there's a context in addition to what the database has, you'll want to do it at the code level. Hope that helps.
来源:https://stackoverflow.com/questions/25195902/php-mysqli-insert-id-0-after-insert-or-update-should-i-read-first