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

作者:iamlaosong

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

select * from tb_evt_mail_clct a, tb_evt_dlv cwhere 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 cwhere 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 cwhere 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 cwhere 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 cwhere 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 awhere 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’)

我喜欢出发。凡是到达了的地方,

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

相关文章:

你感兴趣的文章:

标签云: