+ -
当前位置:首页 → 问答吧 → sql语句比较表记录

sql语句比较表记录

时间:2011-11-25

来源:互联网

3个表:tb1.id,name; tb2.id,f1,f2,f3; tb3.id,f1,f2,f4,f5;3表以id关联,找出tb3比tb2多出来的记录,条件:tb2.id,f1,f2与tb3.id,f1,f2完全相同,并以name,f1,f2,f4,f5显示出来。

作者: chaiwl8869   发布时间: 2011-11-25

补充:忽略其他字段,谢谢!

作者: chaiwl8869   发布时间: 2011-11-25

SQL code
select b.name,a.* 
from tb3  as a
    inner join tb1 as b on a.id=b.id
where not exists(select 1 from tb2 where id=a.ID and f1=a.f1 and f2=a.f2)

作者: roy_88   发布时间: 2011-11-25

我这样做怎么不行?如下:
select tb3.*,tb1.name from tb1 LEFT OUT JOIN tb3 on tb1.id=tb3.id
where not exists(
  select 1 from tb2 where tb3.id=tb2.id
  and tb3.f1=tb2.f1
  and tb3.f2=tb2.f2
)

作者: chaiwl8869   发布时间: 2011-11-25

2#
难道是我的连接出问题了?
我要明天试试再回复。
谢谢!

作者: chaiwl8869   发布时间: 2011-11-25

引用 4 楼 chaiwl8869 的回复:

2#
难道是我的连接出问题了?
我要明天试试再回复。
谢谢!


 LEFT OUT JOIN

问题出在这里,改为inner join

作者: roy_88   发布时间: 2011-11-25

思路应该为取两个表的差集:EXCEPT

作者: yudiw   发布时间: 2011-11-25

select t1.name,t3.* from tb1 as t1 inner join tb3 as t3 on t1.id=t3.id
where t3.id in( select id from ((select id from tb3) except (select id from tb2)) as exceptid )

作者: yudiw   发布时间: 2011-11-25