简体   繁体   English

SQL SELECT 仅当所有项目匹配时

[英]SQL SELECT only when all items match

So I have 2 tables:所以我有2张桌子:

Courses:
-course_ID (primary key)
-course_code
-title

Sections:
-section_ID (primary key)
-course_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:所需的 output 将是:

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?注意条目 (2, ABC, Title1, 1, Monday) 是如何被省略的? 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 课程不存在(除满足您标准的部分之外的所有部分)?

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 所有带有 day = 'Monday' 的部分,从这个结果中,很容易加入 Courses 表来获取课程。

select distinct c.course_id
    from Courses c
        inner join Sections s on s.course_id = c.course_id
    where s.day = 'Monday';

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

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