2017-08-13 58 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子句中,把外連接到內連接。