【问题标题】:Find Missing Pairs in SQL在 SQL 中查找缺失的对
【发布时间】:2010-07-18 16:21:38
【问题描述】:

假设有一个包含 3 个表的关系数据库:

Courses {name, id},
Students {name, id},
Student_Course {student_id, course_id}

我想编写一个 SQL,为我提供不存在的学生-课程对。如果这不可行,至少知道是否缺少对是很好的。

此外,由于这是我想自动化的较大问题的一小部分,因此查看许多不同的方法会很有用。

【问题讨论】:

    标签: sql


    【解决方案1】:

    首先找到所有对,然后删除存在的对(通过left join/not nullnot exists

    select s.id as student_id, c.id as course_id
    from Courses as c
    cross join Students as s
    left join Student_Course as sc on sc.student_id = s.id and sc.course_id = c.id
    where sc.course_id is null -- any sc field defined as "not null"
    

    【讨论】:

      【解决方案2】:
      with Courses as(
      select 1 as id,'Math' as name union all
      select 2 as id,'English' as name union all
      select 3 as id,'Physics' as name union all
      select 4 as id,'Chemistry' as name),
      Students as(
      select 1 as id,'John' as name union all
      select 2 as id,'Joseph' as name union all
      select 3 as id,'George' as name union all
      select 4 as id,'Michael' as name
      ),
      studcrse as(
      select 1 as studid, 1 as crseid union all
      select 1 as studid, 2 as crseid union all
      select 1 as studid, 3 as crseid union all
      select 2 as studid, 3 as crseid union all
      select 2 as studid, 4 as crseid union all
      select 3 as studid, 1 as crseid union all
      select 3 as studid, 2 as crseid union all
      select 3 as studid, 4 as crseid union all
      select 3 as studid, 3 as crseid union all
      select 4 as studid, 4 as crseid )
      
      SELECT A.ID AS studentId,a.name as studentname,b.id as crseid,b.name as crsename
      from Students as a 
      cross join
      Courses as b
      where not exists
      (
      select 1 from studcrse as c
      where c.studid=a.id
      and c.crseid=b.id)
      

      【讨论】:

      • 看起来它必须打破一些设计准则,在查询中指定所有数据,以查找丢失的信息似乎并不自然
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多