【问题标题】:Outer join not showing extra entries外部联接不显示额外条目
【发布时间】:2017-04-27 02:51:35
【问题描述】:

我做了一个查询,其中使用了 3 个表。第一个表具有我需要的所有所需名称。第 2 和第 3 表给了我那些有一些账单金额的名字。但我也需要第一个表中的所有名称。

SELECT   a.name,
         nvl(c.bill_amount,0)
    FROM  table_1 a left outer join table_2 b
    ON  a.name = b.name
    left outer join table_3 c on B.phone_number = C.phone_number
         AND B.email = C.email
         where  b.status = 'YES'
         and a.VALID = 'Y';

现在,表 b 和 c 给了我有限数量的名字,让我说 5 是哪张账单。但在 table_1 中,有 10 个名称。我想在他们的名字上也显示 0 bill_amount。我正在使用 Oracle。

【问题讨论】:

  • 把 where 改成这个; 'WHERE (b.status = 'YES' OR b.status IS NULL)' 或将其放入连接中(取出 where 子句)'AND b.status = 'YES''

标签: sql database join outer-join


【解决方案1】:

上面的答案是对的,我只是想更准确一点。事实上,当左连接不匹配时,右侧表的列被设置为NULL

实际上 NULL 总是在 SQL 中传播值,因此如果连接不进行数学运算,则 b.status = 'YES' 具有值 NULL,然后谓词也不匹配。

处理此问题的一般方法是(b.status = 'YES' or b.name IS NULL):因为b.name 是连接列,当且仅当连接不匹配时它才为空,b.status 可能不是这种情况。

因为NULL 正在传播,所以您不能使用field = NULL,而是使用field IS NULL

但是在join子句中更清楚的时候也可以。

【讨论】:

  • 我遇到了与您指出的相同的问题,未考虑 b.status = 'YES' 条件。当我取出它的值时,状态为 NULL。但我只想要那些 status = 'YES'
【解决方案2】:

在右边的故事上应用where 子句基本上使它成为一个内连接。要保留它OUTER,请将条件放在连接条件中

试试:

SELECT   a.name,
         nvl(c.bill_amount,0)
FROM  table_1 a 
left outer join table_2 b
  ON  a.name = b.name
  and b.status = 'YES'  -- Put it here
left outer join table_3 c 
  on B.phone_number = C.phone_number
  AND B.email = C.email
where a.VALID = 'Y';    -- Only items from the left hand table should go in the where clause

【讨论】:

  • 它解决了大部分问题,但现在我得到了冗余数据。
  • @Akshay 冗余数据?如果你得到重复,使用DISTINCT
  • 你能帮我解决这个问题吗? stackoverflow.com/questions/41541100/…
  • 我遇到了这个问题,没有考虑到 b.status = 'YES' 条件。当我取出它的值时,状态为 NULL。但我只想要那些 status = 'YES'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 2017-01-25
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多