SQL SELECT only when all items match
So I have 2 tables:
Courses: -course_ID (primary key) -course_code -title Sections: -section_ID (primary key) -cour开发者_如何学编程se_ID (foreign key) -day
Each course has a number of sections that belong to it. Let's use an example.
The tables:
course_ID course_code title
1 ABC Title1
2 BBC Title2
section_ID course_ID day
1 1 Monday
2 1 Tuesday
3 2 Monday
4 2 Monday
I want to be able to run a query that asks for all courses that give me ONLY the ones where all of their sections fit a certain criteria. So in this case, let's say I want to see "All the courses which have ALL of their sections on Monday". The desired output would be:
course_ID course_code title section_ID day
2 BBC Title2 3 Monday
2 BBC Title2 4 Monday
Notice how the entry (2, ABC, Title1, 1, Monday) is omitted? I can't seem to think of a way to do this. Thanks in advance!
Try this:
SELECT *
FROM courses c1
WHERE NOT EXISTS
(
SELECT 1
FROM sections c2
WHERE c1.course_id = c2.course_id
AND c2.day <> 'Monday'
)
SELECT * FROM Courses WHERE course_ID NOT IN (SELECT DISTINCT course_ID FROM Sections WHERE day != 'Monday')
Perhaps select courses where not exists (all sections except the sections that satisfy your criteria)?
SELECT c.*
FROM Courses c
WHERE NOT EXISTS (SELECT NULL FROM
Sections s
WHERE Day <> Monday
and s.CourseID = c.CourseID)
select * from Sections s1
where not exists (
select 1 from Sections s2
where s1.course_ID = s2.course_ID and s1.day <> s2.day)
It's saying to pull all sections where a record under the same course doesn't have a different day. That means you get single records as well as multiple records, so long as the days are the same.
You should select all the sections with day = 'Monday' and from that result, it's easy to join with the Courses table to get the courses.
select distinct c.course_id
from Courses c
inner join Sections s on s.course_id = c.course_id
where s.day = 'Monday';
精彩评论