【问题标题】:Joining tables when a condition is not met - SQL Oracle不满足条件时连接表 - SQL Oracle
【发布时间】:2022-07-19 20:29:17
【问题描述】:

我有以下两张表:

~ 我想要做什么:我想通过加入数量和 YYYY_MM 将表 2 (t2) 中的价格附加到表 1 (t1)。每个 t2.price 在一定的时间范围内(t2.Price_Active_Date_From 和 t2.Price_Active_Date_To)是活跃的,并且 t1.Order_Date 应该在这个范围内。当该订单日期没有有效价格时,我希望结果返回 null。

所以结果应该是这样的:

到目前为止,我在下面尝试过,当某个日期有价格时,它可以获取 Price_Active_At_Order,但是当没有有效价格时它不起作用。如何在联接中添加条件以使其有效?:

select distinct
t1.Product_NR,
t1.Customer,
t1.Quantity,
t2.Price as Price_Active_At_Order,
t1.Order_YYYYMM as Order_Date

from Table_1 t1
join Table_2 t2 on t1.Product_NR = t2.Product_NR
                and t1.Quantity = t2.Quantity
                and t1.Order_YYYYMM between t2.Price_Active_Date_From and t2.Price_Active_Date_To

【问题讨论】:

  • [inner] join 更改为 left join

标签: sql oracle


【解决方案1】:

如果没有找到匹配的结果,Inner Join 返回空。如果返回空响应,您可以在代码级别处理它以设置空值。但是在 SQL 中,您只会得到空结果。

如果您仍想获得 NULL 值,您可以使用 LEFT Join 将与条件不匹配的行的值返回为连接右侧表的 null。

右连接也是如此。

当使用Left Join、Right Join、Full (Outer) Join时,可以返回NULL值,而(inner) join,cross join不会返回NULL值。

为了便于理解,您可以通过此链接进行 SQL 连接: https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/

并回答以下问题: https://docs.microsoft.com/en-us/answers/questions/99875/sql-query-full-join-multiple-tables-but-return-nul.html

【讨论】:

    猜你喜欢
    • 2019-04-29
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2018-09-24
    • 2013-07-23
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多