注册 登录
编程论坛 SQL Server论坛

显示两表中不相同的字符

anjincheng 发布于 2007-01-16 21:37, 525 次点击

各老师:
有表A
ID NAME1
1 张三
2 李四
3 王二
4 麻子
.................

表B
ID NAME2
1 张三
2 李四
.................

我想在结果中显示:
还没有签到的有:王二 麻子

请问各位老师,SQL语句怎么实现?感谢!

7 回复
#2
怎么回事2007-01-16 21:55
用not exists试一下吧。
#3
bygg2007-01-17 09:42
select NAME1 from 表A where ID not in(select ID from 表B)
#4
accpfriend2007-01-17 09:56
select A.Name from A where A.ID not exists(select ID from B)
#5
棉花糖ONE2007-01-17 11:40
楼上的注意一下,not in 和 not exists的区别
#6
accpfriend2007-01-17 12:59


对于not in 和 not exists的性能区别:
not in 只有当子查询中,select 关键字后的字段有not null约束或者有这种暗示时用not in,另外如果主查询中表大,子查询中的表小但是记录多,则应当使用not in,并使用anti hash join.
如果主查询表中记录少,子查询表中记录多,并有索引,可以使用not exists,另外not in最好也可以用/*+ HASH_AJ */或者外连接+is null
NOT IN 在基于成本的应用中较好

比如:
select .....
from rollup R
where not exists ( select 'Found' from title T
where R.source_id = T.Title_ID);

改成(佳)

select ......
from title T, rollup R
where R.source_id = T.Title_id(+)
and T.Title_id is null;

或者(佳)
sql> select /*+ HASH_AJ */ ...
from rollup R
where ource_id NOT IN ( select ource_id
from title T
where ource_id IS NOT NULL )

注意:上面只是从理论上提出了一些建议,最好的原则是大家在上面的基础上,能够使用执行计划来分析,得出最佳的语句的写法
希望大家提出异议

#7
棉花糖ONE2007-01-17 13:01
select .....
from rollup R
where not exists ( select 'Found' from title T where R.source_id = T.Title_ID);书上好象说这种最佳
#8
bygg2007-01-17 13:31
呵呵,谢谢
1