对于非现有行,Oracle Outer连接返回0值

时间:2014-05-16 15:07:57

标签: sql oracle outer-join

我有2张桌子

Person
--------------------
id   name   dept_id
---------------------
1   x        1
2   y        1
3   z        2

Feedback
------------------------------------
person_id  f_date  positive  negative 
------------------------------------
1    2014-05-05    10     4
1    2014-05-15    5      3
2    2014-05-11    3      8

现在我的查询是

SELECT p.id, 
       nvl(sum(positive),0) AS pf,
       nvl(sum(negative),0) AS nf 
  FROM person p 
  LEFT OUTER JOIN feedback f ON p.id = f.person_id
 WHERE f_date BETWEEN to_date('2014-05-04', 'YYYY-MM-DD')
                  AND to_date('2014-05-16', 'YYYY-MM-DD')
 GROUP BY p.id
 ORDER BY p.id;

我希望看到

id   pf    nf
---------------
1   15     7
2   3      8
3   0      0

但是我没有看到3的数据。事实上,我得到的数据只有在反馈表中存在行时,就好像它是一个equi连接一样。

1 个答案:

答案 0 :(得分:2)

您的WHERE子句正在将外部联接转换为内部联接。解决方案是将条件移动到ON子句:

SELECT p.id, nvl(sum(positive),0) as pf, nvl(sum(negative),0) as nf 
FROM person p left outer JOIN
     feedback f
     on p.id = f.person_id and
        f.f_date between to_date('2014-05-04', 'YYYY-MM-DD') AND to_date('2014-05-16', 'YYYY-MM-DD')
GROUP BY p.id
ORDER BY p.id;