两个不同的表,其中有某一个字段是相同的,但此字段表达式的数量不同,如何查两表相同字段下不同的数据?

如表A中有(spbh,spmc,yesl)表B中有(spbh,jsrq),其中A表中的spbh有一万条记录,B表中有7千条记录,AB两表中的spbh有5000条记录是相同... 如 表A 中有(spbh,spmc,yesl) 表B中有(spbh,jsrq),其中A表中的spbh有一万条记录,B表中有7千条记录,AB两表中的spbh有5000条记录是相同的,如何查询spbh下出不相同的记录数据,(加个条件;A中的yesl《》0,B表中的jsrq》=‘2013-**-**’)请高人指点该怎么写sql语句,谢谢! 展开
 我来答
tjrmgs
2013-11-02 · TA获得超过5764个赞
知道大有可为答主
回答量:2161
采纳率:94%
帮助的人:992万
展开全部
这是一个求两表非交集的问题。
由于A,B二表结构不同,结果集我就不予合并在一起了。这里分两次查询

1)求A表中spbh与B表中spbh不相同的那些记录

方法1(使用not in)
select * from A where spbh not in (select spbh from B) and yesl<> 0;

方法2(使用not exists)
select * from A where not exists(select * from B where B.spbh=A.spbh) and A.yesl<> 0;

方法3(使用左联接left join)
select t1.spbh,t1.spmc,t1.yesl from
(select A.*,t.spbh as flag from A left join (select distinct spbh from B)t
on t.spbh=A.spbh where A.yesl<>0)t1
where t1.flag is null

2)求B表中spbh与A表中spbh不相同的那些记录

方法1(使用not in)
select * from B where spbh not in (select spbh from A) and B.jsrq>='2013-11-02';

方法2(使用not exixts)
select * from B where not exists(select * from A where A.spbh=B.spbh) and B.jsrq>='2013-11-02';

方法3(使用左联接left join)
select t1.spbh,t1.jsrq from
(select B.*,t.spbh as flag from B left join (select distinct spbh from A)t
on t.spbh=B.spbh where B.jsrq>='2013-11-02')t1
where t1.flag is null

说明:
方法1,逻辑上最容易理解,但是大数据表时应避免使用,因为不管有无可以利用的索引的情况下都会导致执行效率上的悲剧!语句执行起来可能要耗费很长的时间;

方法2,如果两表的spbh字段上建有索引,其效率将会非常之高,此时应设为首选方案。但是无索引的情况下运行于大数据表时也出现效率悲剧,应避免使用;

方法3,无可利用的索引时此方法应设为首选,其运行效率优于前两种。有可被利用索引的情况下,以方法二最优。
tianlanyijiu1
2013-11-02 · TA获得超过195个赞
知道小有建树答主
回答量:294
采纳率:100%
帮助的人:146万
展开全部
(select * from A a where a.spbh not in (select b.spbh from B b where b.spbh = a. spbh) and a.yesl <>0)
union
(select * from B b where b.spbh not in (select a.spbh from A a where a.spbh = b. spbh) and b.jsrq >= to_date('2013-10-01','yyyy-MM-dd'))
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式