多表内连接查询关键字不对应时要注意的一个问题

作者:iamlaosong

多表连接查询中最常用的事内连接,内连接中最常用的是等值连接,即在连接条件中使用等于号(=)运算符比较被连接列的列值,其查询结果中列出被连接表中的所有列,包括其中的重复列。例如:

select *  from tb_evt_mail_clct a, tb_evt_dlv c
 where a.clct_date between to_date('2015-6-11', 'yyyy-mm-dd') and
       to_date('2015-6-11', 'yyyy-mm-dd')
   and a.mail_num=c.mail_num;

上述查询中,A表(收寄表)和C表(投递表)中的邮件号码mail_num不一定是一一对应的,有可能A表中存在的,C表中不存在,按上面的语句查询,这些邮件将不会出现,如果需要出现,我们一般在等式的右边添加一个“(+)”,这样就可以列出A表中的所有内容,如下所示:

select *  from tb_evt_mail_clct a, tb_evt_dlv c
 where a.clct_date between to_date('2015-6-11', 'yyyy-mm-dd') and
       to_date('2015-6-11', 'yyyy-mm-dd')
   and a.mail_num=c.mail_num(+);

如果我们要统计A表中存在C表中不存在的邮件量(未投递邮件量),可以用下面语句:

select count(*)  from tb_evt_mail_clct a, tb_evt_dlv c
 where a.clct_date between to_date('2015-6-11', 'yyyy-mm-dd') and
       to_date('2015-6-11', 'yyyy-mm-dd')
   and a.mail_num=c.mail_num(+)

   and c.mail_num is null;

我们可以用下面语句统计妥投邮件量,妥投的条件是c.dlv_sts_code = 'I',即:

select count(*)  from tb_evt_mail_clct a, tb_evt_dlv c
 where a.clct_date between to_date('2015-6-11', 'yyyy-mm-dd') and
       to_date('2015-6-11', 'yyyy-mm-dd')
   and a.mail_num=c.mail_num(+)

   and c.dlv_sts_code = 'I';


但是如果我们需要统计未妥投邮件量,下面语句是不成立的,统计的结果为0:

select count(*)  from tb_evt_mail_clct a, tb_evt_dlv c
 where a.clct_date between to_date('2015-6-11', 'yyyy-mm-dd') and
       to_date('2015-6-11', 'yyyy-mm-dd')
   and a.mail_num=c.mail_num(+)

   and c.dlv_sts_code = 'I'

   and c.mail_num is null;

这是因为,c.mail_num is null这个条件成立时,c.dlv_sts_code 的值也是null,不可能等于‘I',所以,统计的结果为0,也就是说,当统计C表mail_num为空的量时,是不能用其它筛选条件的,确实需要统计的话,需要用下面语句:
select count(*)  from tb_evt_mail_clct a
 where a.clct_date between to_date('2015-6-11', 'yyyy-mm-dd') and
       to_date('2015-6-11', 'yyyy-mm-dd')
   and not exists (select 1
          from tb_evt_dlv c
         where c.mail_num = a.mail_num
           and c.dlv_sts_code = 'I')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值