如何使用Oracle中的连接从一个表中删除数据?

Aru*_*amy 2 oracle oracle11g delete-row

我正在尝试从一个具有连接条件的表中删除数据.

我试过这个

Delete test_one from test_one Val 
                join test_two En  
                  on Val.Map_Fromphyid=En.Fromphyid And            
                     Val.Map_Tophyid=En.Tophyid     And 
                     Val.Map_Relname=En.Relname 
                  Where Val.Result='NOT Done'
Run Code Online (Sandbox Code Playgroud)

但是这给了我这个错误

"SQL命令未正确结束"

我知道我可以通过这种方式做到这一点

Delete From test_one 
       Where Phyid In (Select Val.Phyid From test_one Val 
                                        join test_two En  
                                        on Val.Map_Fromphyid=En.Fromphyid And
                                           Val.Map_Tophyid=En.Tophyid And 
                                           Val.Map_Relname=En.Relname 
                                        Where Val.Result='NOT Done');
Run Code Online (Sandbox Code Playgroud)

第一种方法有什么问题?如果没有子查询如何实现那个东西是错误的?

我见过这个问题.我正在寻找没有任何子查询的查询.我只用子查询找到答案.

Tho*_*ner 6

您正在动态创建视图(即,而不是delete from t从您要从查询中获取的记录中删除要删除的表delete from <query>.

为了从这样的临时视图中进行选择,您需要使用parantheses(例如,select * from (select from b)而不是select * from select from b.

使用UPDATE语句它是一样的.所以要么从表中删除:

delete [from] test_one where ...
Run Code Online (Sandbox Code Playgroud)

或者从一个角度来看

delete [from] (select * from test_one ...)
Run Code Online (Sandbox Code Playgroud)

但不要忘记括号.并且不要将表视图命名为

delete [from] test_one [from] (select * from test_one ...)
Run Code Online (Sandbox Code Playgroud)

这就是你在做什么.

我发现在可能的情况下直接从表中删除是比较好的,因为从Oracle中删除临时视图对我来说似乎有点模糊,我认为它不太可读:

  • delete from (select * from a join b on a.x = b.x) 从a删除
  • delete from (select * from b join a on a.x = b.x) 删除b
  • delete from (select a.* from b join a on a.x = b.x) 从a删除

至少在我的Oracle版本中发生的是11g.

至于你的DELETE语句,我建议你这样写:

delete from test_one val 
where result = 'NOT Done'
and exists
(
  select *
  from test_two en  
  where en.fromphyid = val.map_fromphyid 
  and en.tophyid = val.map_tophyid     
  and en.relname = val.map_relname 
);
Run Code Online (Sandbox Code Playgroud)

我认为这是可读的:从表test_one中删除所有'NOT Done'记录,其中也存在表test_two中的条目.