SQL Join三个表保持不重叠的空值

时间:2017-02-28 08:11:01

标签: mysql sql join presto

我基本上在数据库中有2个表,加上一个日期表,我认为我需要将它们连接在一起以达到预期的效果。

FOOS

@ViewChild('myElement') ref: ElementRef;
service: YoutubePlayerService = new YoutubePlayerService(this.someZone);
player: YoutubePlayer = new YoutubePlayer(this.service, this.ref);

酒吧

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
...

我目前正在做的是选择我的日期表,然后将foos加入日期,然后离开加入吧到日期。

问题是,这给了我以下结果

date       | bars | foos
-------------------------
2016-01-01   Null   2
2016-01-02   9      3
2016-01-03   8      4
2016-01-04   7      Null

如果条形图和foos都为null,我不希望返回日期。我可以通过这种方式进行渲染,但我不确定这是最有效的选择方式,即:

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
...

2 个答案:

答案 0 :(得分:1)

使用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 |
+------------+------+------+

答案 1 :(得分:0)

对于此查询,使用以下内容似乎足够高效。

where (bars is not null or foos is not null)