我需要先选择不在第二个选择中的值。
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。
答案 0 :(得分:0)
您可以使用LEFT JOIN
:
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
行。
答案 1 :(得分:0)
这通常可以使用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) )