【发布时间】:2010-07-18 16:21:38
【问题描述】:
假设有一个包含 3 个表的关系数据库:
Courses {name, id},
Students {name, id},
Student_Course {student_id, course_id}
我想编写一个 SQL,为我提供不存在的学生-课程对。如果这不可行,至少知道是否缺少对是很好的。
此外,由于这是我想自动化的较大问题的一小部分,因此查看许多不同的方法会很有用。
【问题讨论】:
标签: sql
假设有一个包含 3 个表的关系数据库:
Courses {name, id},
Students {name, id},
Student_Course {student_id, course_id}
我想编写一个 SQL,为我提供不存在的学生-课程对。如果这不可行,至少知道是否缺少对是很好的。
此外,由于这是我想自动化的较大问题的一小部分,因此查看许多不同的方法会很有用。
【问题讨论】:
标签: sql
首先找到所有对,然后删除存在的对(通过left join/not null 或not 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)
【讨论】: