2017-08-13 60 views
0

我有两个表,transactionsdates。一个日期可能有一个或多个交易。我需要获得有或没有特定账户交易的日期列表(账户号码为111)。需要了解SQL SELECT中的特定左外连接行为

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作品)。为什么会发生?

+0

可能重复的[SQL不同之间左加入...和左加入on..where](https://stackoverflow.com/questions/44696051/sql-different-between-left-join-on-and - 左联接上,在哪里) –

回答

2

条件在第二个表需要进入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.accountNULLwhere子句中,把外连接到内连接。