[英]Need to understand specific LEFT OUTER JOIN behavior in SQL SELECT
I have two tables, transactions
and dates
. 我有两个表,
transactions
和dates
。 One date may have one or more transactions. 一个日期可能有一个或多个交易。 I need to get a list of dates with or without transactions of a specific account (account number
111
below). 我需要获取带有或不带有特定帐户交易的日期列表(下面的帐户号
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;
The issue is that when I specify in the condition t.account=111
I don't get the dates on which account 111 did NOT make any transactions. 问题是,当我在条件
t.account=111
指定时,我没有得到帐户111未进行任何交易的日期。
Only if I remove from the condition t.account=111
I DO get the dates with no transactions (ie the LEFT OUTER JOIN
works). 仅当我从条件
t.account=111
删除时,我才获得没有交易的日期(即LEFT OUTER JOIN
起作用)。 Why does this happen? 为什么会这样?
Conditions on the second table need to go into the on
clause: 第二个表上的条件需要
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;
Otherwise, the value of t.account
is NULL
in the where
clause, turning the outer join into an inner join. 否则,
where
子句中t.account
值为NULL
,从而将外部t.account
转换为内部t.account
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.