假設有3臺關係數據庫:尋找失蹤巴黎之SQL
Courses {name, id},
Students {name, id},
Student_Course {student_id, course_id}
我想寫一個SQL,讓我說,不存在學生課程對。如果這是不可行的,至少應該知道是否存在缺失對。
此外,由於這是我想自動化的一個較大問題的一小部分,因此查看許多不同的方法可能會很有用。
假設有3臺關係數據庫:尋找失蹤巴黎之SQL
Courses {name, id},
Students {name, id},
Student_Course {student_id, course_id}
我想寫一個SQL,讓我說,不存在學生課程對。如果這是不可行的,至少應該知道是否存在缺失對。
此外,由於這是我想自動化的一個較大問題的一小部分,因此查看許多不同的方法可能會很有用。
1找出所有對,然後去除存在對(通過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)
看起來它必須打破一些設計原則,指定查詢中的所有數據,尋找失蹤信息似乎不自然 – 2010-07-18 07:54:50
+1的解釋。這應該工作。 – 2010-07-18 07:28:20