我需要具有不在第二选择中的第一选择值。
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。
最佳答案
这通常可以使用not exists
解决:
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) )