Given the two tables below, each ball can have one or more colors.
What would be the most efficient way to update the ball_color_mapping
table when changes are made in a UI?
For example, ball_id = 1
had color_ids
of 1,2,3
and after an update should only have color_id = 2
.
The possible options I see:
- Delete all rows matching the
ball_id
then insert the new values. - Fetch the existing
color_ids
, compare new vs old values and delete/insert.
Option 1 seems like the simplest but would also result in deleting and inserting if the data didn't change. Option 2 would add more operations and complexity since the data needs to be fetched then deleted based on the criteria and new values would be inserted (3 operations + logic vs 2 operations)
For others that encountered this, which option would be more efficient and are there better methods?
ball table:
ball_id | name | brand_id |
---|---|---|
1 | tennis ball | 1 |
2 | pool ball | 2 |
3 | ping pong ball | 1 |
ball_color_mapping table:
ball_id | color_id |
---|---|
1 | 1 |
1 | 2 |
1 | 3 |
2 | 1 |
3 | 2 |
3 | 3 |