I’m developing a stock control database and wish to know what would be the best way to do relationship between products and stocks entities.
Which of below is appropriate? If none, please let me know why and what is your suggestion.
Thanks in advance
PRODUCTS – STOCKS
Based on above entities:
-
If I have
1:1relationship, looks like I’ll have to reduce stock
amount in same row by updating the row withUPDATEstatement. -
If I have
1:nrelationship, looks like I’ll have to add a new row
with updated stock amount in it withINSERTstatement.
IMPORTANT POINTS
-
There will be concurrent users to manipulate stock like increasing and/or reducing so
[ACID][1]is important point. -
Stock amountis non-negative value.
Depends on what you are trying to accomplish.
If you need a simple number that describes the available quantity of a product, just store it as a field in the product table. Updating it in a single statement is atomic:
Alternatively, you could do something like this:
Note the FOR UPDATE which locks the row until the COMMIT and prevents the anomalies that would otherwise be possible in a concurrent environment.
Without FOR UPDATE, just the regular ACID guarantees are not enough. For example:
Suddenly, the resulting AMOUNT in the table is 5 + 3 = 8, even though it should have been 5 + 2 + 3 = 10. One of the changes is lost – whoever commits last wins.
If you need a history of product amounts, or need to track individual “instances” of products, then yes, you’d need a separate table in a 1:N relationship, which may have its own locking challenges in the concurrent environment.
Unfortunately, MySQL doesn’t enforce CHECK constraints, but for this specific case, you can simply use one of the UNSIGNED data types.