2017-08-13 5 views
0

私はtransactionsdatesの2つのテーブルを持っています。 1つの日付は1つ以上のトランザクションを持つことができます。特定の口座(口座番号111以下)の取引の有無にかかわらず、日付のリストを取得する必要があります。SQL SELECTで特定のLEFT OUTER JOINの動作を理解する必要があります

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の左結合]と[左結合...]の可能な複製(https://stackoverflow.com/questions/44696051/sql-different-between-left-join-on-and) -left-join-on-where) –

答えて

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.accountの値は、内側に加わる外部結合を回し、where句でNULLあります。

関連する問題