SQL连接三个表保持不重叠的空值
SQL Join three tables keep non-overlapping null values
我基本上在一个数据库中有 2 个 table,加上一个日期 table,我认为我需要将它们连接在一起才能达到预期的效果。
福斯
date | foos
------------------
2016-01-01 2
2016-01-02 3
2016-01-03 4
酒吧
date | bars
------------------
2016-01-02 9
2016-01-03 8
2016-01-04 7
日期
dates
----------
2016-01-01
2016-01-02
2016-01-03
2016-01-04
...
想要的返回值
date | bars | foos
-------------------------
2016-01-01 Null 2
2016-01-02 9 3
2016-01-03 8 4
2016-01-04 7 Null
我目前正在做的是 select 设置我的日期 table,然后将 foos 加入日期,然后将 bars 加入日期。
问题是这给了我以下结果
date | bars | foos
-------------------------
2016-01-01 Null 2
2016-01-02 9 3
2016-01-03 8 4
2016-01-04 7 Null
2016-01-05 Null Null
2016-01-06 Null Null
2016-01-07 Null Null
...
如果 bars 和 foos 都为空,我不希望返回日期。我可以让它以那种方式呈现,但我不确定这是 select 的最有效方式,即:
where (bars is not null or foos is not null)
使用以下内容似乎足以满足此查询的要求。
where (bars is not null or foos is not null)
尝试使用 left outer join
select d.dates,b.bars,f.foos from dates d
left outer join bars b on d.dates = b.date
left outer join foos f on d.dates = f.date;
+------------+------+------+
| dates | bars | foos |
+------------+------+------+
| 2016-01-02 | 9 | 3 |
| 2016-01-03 | 8 | 4 |
| 2016-01-04 | 7 | NULL |
| 2016-01-01 | NULL | 2 |
+------------+------+------+
我基本上在一个数据库中有 2 个 table,加上一个日期 table,我认为我需要将它们连接在一起才能达到预期的效果。
福斯
date | foos
------------------
2016-01-01 2
2016-01-02 3
2016-01-03 4
酒吧
date | bars
------------------
2016-01-02 9
2016-01-03 8
2016-01-04 7
日期
dates
----------
2016-01-01
2016-01-02
2016-01-03
2016-01-04
...
想要的返回值
date | bars | foos
-------------------------
2016-01-01 Null 2
2016-01-02 9 3
2016-01-03 8 4
2016-01-04 7 Null
我目前正在做的是 select 设置我的日期 table,然后将 foos 加入日期,然后将 bars 加入日期。
问题是这给了我以下结果
date | bars | foos
-------------------------
2016-01-01 Null 2
2016-01-02 9 3
2016-01-03 8 4
2016-01-04 7 Null
2016-01-05 Null Null
2016-01-06 Null Null
2016-01-07 Null Null
...
如果 bars 和 foos 都为空,我不希望返回日期。我可以让它以那种方式呈现,但我不确定这是 select 的最有效方式,即:
where (bars is not null or foos is not null)
使用以下内容似乎足以满足此查询的要求。
where (bars is not null or foos is not null)
尝试使用 left outer join
select d.dates,b.bars,f.foos from dates d
left outer join bars b on d.dates = b.date
left outer join foos f on d.dates = f.date;
+------------+------+------+
| dates | bars | foos |
+------------+------+------+
| 2016-01-02 | 9 | 3 |
| 2016-01-03 | 8 | 4 |
| 2016-01-04 | 7 | NULL |
| 2016-01-01 | NULL | 2 |
+------------+------+------+