除了mysql上的可选

除了mysql上的可选,mysql,database,Mysql,Database,我需要第一次选择的值不在第二次选择中 select tnum,user from resp order by tnum, user except select test.tnum,cursa.user from cursa inner join test on test.curso = cursa.curso; 结果: select tnum,user from resp order by tnum, user;= tnum user 1 1 1 7 1

我需要第一次选择的值不在第二次选择中

select tnum,user from resp order by tnum, user
except
select test.tnum,cursa.user from cursa inner join test on test.curso = cursa.curso;
结果:

select tnum,user from resp order by tnum, user;=
tnum    user
1       1
1       7
1       8
1       10
2       7

select test.tnum,cursa.user from cursa inner join test on test.curso = cursa.curso;=
tnum    user
1       1
1       7
1       8
1       10
2       1
2       8
3       1
3       7
3       8
3       10
4       1
4       7
4       8
4       10
我需要返回tnum 2和用户7


您可以使用
左连接

select tnum, user 
from resp AS t1
left join (
   select test.tnum, cursa.user 
   from cursa 
   inner join test 
   on test.curso = cursa.curso ) AS t2
ON t1.tnum = t2.tnum AND t1.user = t2.user
WHERE t2.num IS NULL AND t2.user IS NULL
order by tnum, user

WHERE
子句过滤掉与派生表行相关的所有
resp
行。

这通常可以使用
不存在来解决:

select r.tnum, r.user
from resp r
where not exists (select 1
                  from cursa c inner join
                       test t
                       on t.curso = c.curso
                  where t.tnum = r.tnum and c.user = r.user
                 );
这与处理
NULL
值的方式略有不同。如果
rep.tnum
resp.user
NULL
,则不会删除该行

如果可能,则将子查询中的
where
子句更改为:

where (t.tnum = r.tnum or (t.tnum is null and r.tnum is null) ) and
      (c.user = r.user or (c.user is null and r.user is null) )