Delete from multiple tables in one single query

拟墨画扇 提交于 2019-12-25 16:24:49

问题


I am a beginner in DB2. I want to delete from 2 tables using one query. The reason why I want to do that is because the condition for delete is complex and implies JOIN in big tables. I don't want to do the same query twice. Basically I want something like that :

DELETE from table1 t1, table2 t2 
WHERE t1.ID = t2.ID 
AND ID in ( -- some select and JOIN stuff) 

回答1:


With DB2 for LUW you can do something like this using the data change table reference:

WITH lst (id) as ( -- some select and JOIN stuff),
lst1 (id) as (
  SELECT id FROM OLD TABLE (
    DELETE FROM table1 WHERE id IN (SELECT id FROM lst)
  )
)
SELECT id FROM OLD TABLE (
  DELETE FROM table2 WHERE id IN (SELECT id FROM lst1)
)

OLD TABLE (DELETE ...) is the data change table reference, which contains in this case all rows that have been deleted by the enclosed DELETE.

I don't think this trick is supported on other DB2 platforms, althought it might be in DB2 for z/OS v.11 -- I have no way of testing that though.




回答2:


Short answer: You cant do that

My thoughts

  • Running the same query twice should't be much issues specially because db usually get some cache.
  • If the problem is performance maybe the problem is on the query, the server cpu or the disk.

Possible solution

  • Create a trigger on table1 on delete where you will also delete same item on table 2


来源:https://stackoverflow.com/questions/32099521/delete-from-multiple-tables-in-one-single-query

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