简体   繁体   中英

SQL - Where In one table not the other (Multiple Fields)

I have the following tables

桌子

Their Relationship is the following: modulos holds all modules, and mods_alunos holds only the modules each student made(nInterno identifies the student)

    select modulos.codDisc, modulos.numero from modulos
    left join mods_alunos
    on modulos.codDisc=mods_alunos.codDisc
    and modulos.numero=mods_alunos.numero
    where 
    (mods_alunos.codDisc is null 
    and mods_alunos.numero is null
    )

This query gives the modules missing but doesnt take the student into account

I'm looking for a query that list the modules a certain student is missing

EDIT 1 - Sample Data

Modulos

codDisc | numero
------- | ------
1       | 1
1       | 2
1       | 3
2       | 1
2       | 2

mods_alunos

nInterno | codDisc  | numero
-------- | -------- | ------
11       | 1        | 1
11       | 1        | 2
11       | 1        | 3
11       | 2        | 1
12       | 2        | 2

With this example what i want is a query that gives me (codDisc 2, numero 2) when i ask what modules is student 11 missing

You will need to work from your Student table, not the linking table. try this:

select s.Id, m.codDisc, m.numero 
from student s
cross join modulos m
where not exists(select *
                 from mods_alunos ma 
                 where ma.codDisc = m.codDisc 
                 and ma.numero = m.numero
                 and ma.nInterno = s.Id)

Where student is your student table, and s.Id is your Student ID

UPDATE: `EXCEPT is not supported by MySQL.

Simply use EXCEPT :

 
 
 
 
  
  
  select coddisc, numero from modulos except select coddisc, numero from mods_alunos where ninterno = 123;
 
 
  

NOT IN would be an alternative, though slightly more complicated, so I'd go with EXCEPT as mentioned.

select coddisc, numero from modulos
where (coddisc, numero) not in
  (select coddisc, numero from mods_alunos where ninterno = 123);

您可以执行以下操作:

SELECT * FROM modulus WHERE codeDisc NOT IN(SELECT codeDisc  FROM mods_alunos WHERE nInterno=?) AND numero NOT IN (SELECT numero FROM mods_alunos WHERE nInterno=?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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