【发布时间】:2016-06-14 07:29:51
【问题描述】:
我有两张桌子
tableA
Accountid
-----------
10
11
12
tableB
Accountid | Date |
--------------------------------------------
10 | 2016-02-02 |
11 | 2016-02-02 |
11 | 2016-02-02 |
15 | 2016-02-03 |
我期待像
这样的输出Accountid | ID |
------------------------------------
10 | 10 |
11 | 11 |
12 | NULL |
我正在运行这个查询
select A.accountid,b.accountid as ID
from tableA as A
left join tableB as B on a.accountid=b.accountid
where b.date between '2016-02-02' and '2016-02-02'
但它给了我输出,我不确定我哪里出错了
Accountid | ID |
-----------------------------------
10 | 10 |
11 | 11 |
我正在使用 MSSQL 数据库。
【问题讨论】:
-
将
b.date between '2016-02-02' and '2016-02-02'移动到连接条件中。将其放入where会将外连接变为内连接 -
这是由于 b.date 在 '2016-02-02' 和 '2016-02-02' 之间......
-
@a_horse_with_no_name 它的 where 条件将 join 的含义从左转为内是不正确的。只有当他将 a.accountid=b.accountid 放在 where 子句中时,这才是正确的
-
@MtwStark:如果外部表上的条件使用不应为空的值,那么
where条件将使查询的行为类似于内部联接。跨度> -
@a_horse_with_no_name 我们不知道日期字段是否为 NOT NULL,首先执行连接条件,它可以检索带有或不带有可为空字段的任何行.. 您使用 WHERE 子句过滤的内容可能是与 INNER JOIN 的结果不同
标签: sql sql-server outer-join