简体   繁体   English

在SQL中找到丢失的对

[英]Find Missing Pairs in SQL

Assume there's a relational database with 3 tables: 假设有一个包含3个表的关系数据库:

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

I want to write an SQL that gives me the student-course pairs that do NOT exist. 我想写一个SQL,它给了我不存在的学生课程对。 If that is not feasible, at least it'd be good to know if there are missing pairs or not. 如果这不可行,至少知道是否缺少对是很好的。

Also, since this is a small part of a larger problem I'd like to automate, seeing many different ways of doing it would be useful. 此外,由于这是一个较大问题的一小部分,我想自动化,看到许多不同的方法,这将是有用的。

1st find all pairs and then remove pairs present (either by left join/not null or not exists ) 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"
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM