I want to update my junction table's row. Not literally update, insert only new tuples and drop the ones that were not inserted.
Here's my tables:
users table
-----------------------
|user_id |FullName |
-----------------------
|1 | John |
|2 | Michael |
|3 | Bryce |
addresses table
-----------------------------------------
|address_id| country | city |
-----------------------------------------
| 1 | USA | New-York |
| 2 | Russia | Moscow |
| 3 | Germany | Berlin |
| 4 | UK | London |
This is the Junction table to connect the two now.
"user_address"
------------------------
| user_id | address_id |
------------------------
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
For example I want to insert a new values in my junction and make it like this:
------------------------
| user_id | address_id |
------------------------
| 1 | 1 |
| 1 | 3 |
| 2 | 4 |
And, yeah, I can just do that:
DELETE FROM user_address WHERE address_id = 1;
INSERT INTO user_address VALUES (1, 3);
But, what if I'll have 1 million of rows, and user want to delete just one row.
In this case I'll delete all 1 million and insert 999.999.999 only for ONE row.
So, how can I insert only new rows and drop the ones that were not inserted for me?
P.S. I'm using PostgreSQL.
UPDATE
Hope this screenshots will explain my problem.
Here's my junction table:
I'm trying to update users for address - change user_id in junction:
UPDATE user_address SET user_id = 100 WHERE address_id = 25 RETURNING user_id
But if I use this query it will change both user_id to 100 when I want to have only one row with user_id = 100
So, question is How to avoid duplicates in junction's table update.