Oracle SQL “deep update”

隐身守侯 提交于 2020-01-16 10:13:02

问题


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:

  1. All the Items in the Bag are already in the database. In this case, I just need to update the Items in the database.
  2. 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
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!