请教如何写语句查找到两表没有关联上的记录

[复制链接]
查看11 | 回复9 | 2007-7-4 17:27:50 | 显示全部楼层 |阅读模式
假设有a,b两个表,a表有id字段,b表有targetid字段,它们是相互关联的,现在我想要查找有targetid但a表不存在相应的id的记录。请教前辈这个该怎么写?谢谢!
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
select b.*
from a, b
where a.id(+) = b.targetid
and a,id is null;

You also can use minus or exists operators!
[ 本帖最后由 bell6248 于 2008-9-24 15:16 编辑 ]
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
select * from b where targetid not in(select id from a)
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
写法很多
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
谢谢各位大叔!
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
slect b.targetid from a left join b on a.id=b.targetid where a.id isnull
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
你们都成大叔拉!!!!!
select * from table
where xx not in (select bb from table1)
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
原帖由 junsansi 于 2008-9-24 15:14 发表
select * from b where targetid not in(select id from a)

三思给的语句可读性好,不过如果表大的话性能会很差,
2楼给的应该是最快的,
补充一种(效率仅次于2楼的):
select * from b where not exists (select 'x' from a where a.targetid= b.id )
[ 本帖最后由 zouhu007 于 2008-9-24 19:40 编辑 ]
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
SELECT b.*
FROM a,
b
WHERE a.id(+) = b.targetid AND
b.targetid IS NOT NULL AND
a.id IS NULL
回复

使用道具 举报

千问 | 2007-7-4 17:27:50 | 显示全部楼层
原帖由 zouhu007 于 2008-9-24 19:36 发表

三思给的语句可读性好,不过如果表大的话性能会很差,
2楼给的应该是最快的,
补充一种(效率仅次于2楼的):
select * from b where not exists (select 'x' from a where a.targetid= b.id )

三思兄的写法不一定效率差,要看情况,in是基于外部表驱动的,exists是基于内部表驱动的,要看是内表大还是外表大!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行