I’m trying to find a way to insert one or more rows to a table without exceeding a maximum numbers of rows at that point in time defined by the query. I need to do this efficiently and thread safely.
Say for example I have a table that holds information about different pieces of fruit. I need to be able to insert one or more pieces of fruit (all of the same kind) at the same time without exceeding a total number of that type of fruit on the table at any time. What I mean by this is no more than 100 apples, 250 oranges, etc.
⁃ Insert 5 oranges into fruits unless there are more than 245 (250 - 5) oranges already.
⁃ Insert 1 apple into fruits unless there are more than 99 (100 - 1) apples already.
I understand that I could select first to determine if there is space, then insert my data, then select again to make sure I have exceeded the “quota” for that type, but that doesn’t seem efficient. When it comes to multiple threads it seems more like a hack/hammering method to getting it done. My concern and the reason I’d “look back” to check if too many were inserted is between the first select and the insert another connection might come along and insert rows before I get a chance to making my insert overflow those limits.
I’m still learning MySQL and if I haven’t given enough information let me know.
Any thoughts?