【问题标题】:How to use subquery to drop rows from Tab1 which are in Tab2 in Oracle SQL?如何使用子查询从 Oracle SQL 的 Tab2 中的 Tab1 中删除行?
【发布时间】:2021-11-25 13:04:09
【问题描述】:

我在 Oracle SQL 中有如下表:

Tab1

ID
-----
1
2
3

Tab2

ID
-----
3
4
5

我需要从 Tab1 中获取不在 Tab2 中的值。我做了如下查询:

select ID
from Tab1
where ID not in (select ID from Tab2)

上面的查询不起作用,我怎样才能改变它以达到我需要的结果:

ID
---
1
2

我可以补充一点,我更喜欢在这个问题中使用子查询,我如何在 Oracle SQL 中做到这一点?

【问题讨论】:

    标签: sql oracle subquery


    【解决方案1】:

    使用MINUS 集合运算符:

    SQL> with
      2  tab1 (id) as
      3    (select 1 from dual union all
      4     select 2 from dual union all
      5     select 3 from dual
      6    ),
      7  tab2 (id) as
      8    (select 3 from dual union all
      9     select 4 from dual union all
     10     select 5 from dual
     11    )
     12  select id from tab1
     13  minus
     14  select id from tab2;
    
            ID
    ----------
             1
             2
    
    SQL>
    

    顺便说一句,您使用的查询(带有子查询)返回正确的结果;您的意思是说您更喜欢 NOT 使用子查询?

     <snip>
     12  select id from tab1
     13  where id not in (select id from tab2);
    
            ID
    ----------
             1
             2
    

    【讨论】:

    • 不能用子查询吗?
    • 您的查询使用子查询。它有什么问题?
    • 我的子查询查询不起作用:/
    【解决方案2】:

    我试过这段代码,效果很好:

    选择 ID 从表 1 其中 ID 不在(从表 2 中选择 ID)

    【讨论】:

      【解决方案3】:

      您不能从表中DROP行,但您可以 DELETE它们。

      所以更正你的标题

      如何使用子查询DELETE Oracle SQL 中 Tab1 中 Tab2 中的行?

      这样做:

      delete from tab1
      where id  in (select id from tab2);
      
      1 row deleted.
      
      select * from tab1;
      
              ID
      ----------
               1
               2
      

      不要忘记commit 进行更改永久

      【讨论】:

        猜你喜欢
        • 2021-04-22
        • 1970-01-01
        • 1970-01-01
        • 2012-09-22
        • 1970-01-01
        • 2022-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多