【问题标题】:Need to understand specific LEFT OUTER JOIN behavior in SQL SELECT需要了解 SQL SELECT 中特定的 LEFT OUTER JOIN 行为
【发布时间】:2018-01-21 14:45:37
【问题描述】:

我有两张桌子,transactionsdates。一个日期可能有一个或多个交易。我需要获取特定帐户(下面的帐号111)有或没有交易的日期列表。

select d.the_date, t.account, t.amount from dates as d
LEFT OUTER JOIN transactions as t ON t.tx_date=d.the_date
where t.account=111 AND d.the_date>='2016-01-02' and d.the_date<='2017-12-30'
order by d.the_date;

问题是当我在条件t.account=111 中指定时,我没有得到帐户 111 没有进行任何交易的日期。

只有当我从条件t.account=111 中删除时,我才会得到没有交易的日期(即LEFT OUTER JOIN 有效)。为什么会这样?

【问题讨论】:

标签: sql select join left-join


【解决方案1】:

第二张表的条件需要进入on子句:

select d.the_date, t.account, t.amount
from dates d left join
     transactions t 
     on t.tx_date = d.the_date and t.account = 111
where d.the_date >= '2016-01-02' and d.the_date <= '2017-12-30'
order by d.the_date;

否则,t.account 的值在where 子句中为NULL,将外连接变为内连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 2014-08-10
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多