【问题标题】:Deleting records from one table if all records are equal to a specific value如果所有记录都等于特定值,则从一个表中删除记录
【发布时间】:2020-09-22 15:36:52
【问题描述】:

学生桌

Student_ID  School          Home State  Grade      Age
85          Washington St   Colorado    Junior     22
90          Washington St   Washington  Senior     23
81          Oregon          California  Junior     21
21          Washington      Washington  Sophomore  21

考勤表

Student_ID  Active  Date
85          N       9/22/20
85          N       9/21/20
81          Y       9/22/20
81          N       9/21/20

如果我想通过查看谁仍然是活跃学生来清理包含学生信息的表,请在 Oracle 数据库中使用。通过在出勤表中按 Student_ID 排序,我想查找学生是否具有所有 active = 'N' 的值。如果每个学生活动的所有值 = 'N' 那么我知道他们不再是学生,我想从学生表(学生 85)中删除记录。但是,如果仅在每个学生的记录上具有 Active = 'Y',那么我不会删除该学生的任何内容,因为我知道他们仍然处于活动状态(学生 81)。最好的解决方法是什么,我尝试使用 all 运算符,但我一直无法获得所需的结果。以下是我一直在尝试使用的查询。

DELETE /*+ parallel (a) */ FROM STUDENT a 
WHERE ( a.student_ID  = ALL
(SELECT /*+ parallel (b) */ b.student_id, b.active FROM attendance b WHERE b.active = 'N')); 

【问题讨论】:

    标签: sql oracle plsql subquery sql-delete


    【解决方案1】:

    一个选项使用not exists:

    delete from student s
    where not exists (
        select 1 from attendance a where a.student_id = s.student_id and a.active = 'Y'
    )
    

    这也会删除根本没有出勤的学生。如果这不是您想要的,那么您可以使用相关子查询:

    delete from student s
    where (
        select min(active) from attendance a where a.student_id = s.student_id
    ) = 'N'
    

    【讨论】:

      【解决方案2】:

      您可以使用聚合检查“Y”行:

      DELETE 
      FROM STUDENT
      WHERE student_ID IN
       (
         SELECT student_id
         FROM attendance
         GROUP BY student_id
         HAVING MAX(active) = 'N' -- no Y for this student
       ); 
      

      【讨论】:

        【解决方案3】:
        NOT Exists 
        

        将是这里的最佳选择,因为猜测您必须处理一些巨大的桌子。 我第二次 GMB 的第一个查询。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多