Pergunta

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 
)
Foi útil?

Solução

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
)

Outras dicas

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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top