문제

So I am trying to list students that are in at least one class but are not part of a group. My code is showing up 0 results but there should be two. Something is wrong with my where clause. I can get it to show students taking one or more classes, just cant get it to show the ones that are also not part of any group. There is something wrong with my where clause. I have 3 tables that are related. Student which holds student name and ID, Member of, which holds student ID and group ID, and studentgroup which holds group ID.

Code:

select student.lastname
from student inner join enrolled on enrolled.studentid = student.sid
where not exists(
select *
from studentgroup inner join memberof on memberof.groupid = studentgroup.gid 
)
도움이 되었습니까?

해결책

You don't have any condition that states how the student would be associated with the student group. So, the EXISTS always returns true, but you want to see the rows where the EXISTS returns false.

You can add the WHERE in the sub query to associate the student with the group.

SELECT student.lastname
FROM student INNER JOIN enrolled ON enrolled.studentid = student.sid
WHERE NOT exists(
SELECT *
FROM studentgroup INNER JOIN memberof ON memberof.groupid = studentgroup.gid
WHERE student.sid = memberof.studentid
)

다른 팁

what if you changed the where clause from where not exists to where not in? something like

where student.id not in (select distinct student_id from member_of)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top