问题
So I'm not sure what it's called, but I need to figure out how best to do an update that may involve insert, update, and delete operations. Here's the situation: My application has POJO's that are stored in the database. These objects may include lists of other objects that are also stored in the database. For example, a Bag object might have a list of Item objects.
I want to be able to update the Bag. However, there are 3 possible situations:
- All the Items in the Bag are already in the database. In this case, I just need to update the Items in the database.
- There are Items in the Bag that are not in the database. In this case, I need to figure out which Items are new and then insert them
- There are Items in the database that are no longer in the Bag object I am updating. In this case, I need to delete the extra Items from the database.
The obvious solution here is to delete it an re-insert everything. But this is slow and will cause new keys to be generated. Most of the time it is not a problem, but it could potentially cause significant problems down the road.
From my research, I've seen that a MERGE may be useful. However, from what I've read, MERGE's are better for groups of data. It is very likely that I might only want to do an update on a single entry or the list of Items may only contain a single object. In addition, it looks like MERGE can only delete records that were matched.
What is the best way to design this functionality?
回答1:
MERGE is a way to go.
There is a Bag: items=Item1, Item2
There is a BagInDB: bag_id = 1 items=Item1,Item3
So we need to update Item1, add Item2 and delete Item3
1st step (join):
select * from bag full outer join (select * from bagInDB where bag_id = 1)
it will give you
bag_itemName bagInDb_itemName
------------ ----------------
Item1 Item1
Item2 null
null Item3
2nd step (merge)
merge into baginDB b
using(query above) q on b.bag_id = 1 and b.itemName = q.bagInDb_itemName
when matched then
delete where q.bag_itemName is null
<rest of the conditions>
来源:https://stackoverflow.com/questions/23918206/oracle-sql-deep-update