我需要加入2个表,但由于某种原因,我没有得到预期的结果。
表1列出了一年中的所有日期,表2列出了某些日期的数据。我有以下内容:
表1
+------------+
| dates |
+------------+
| 2016-11-01 |
| 2016-11-02 |
| 2016-11-03 |
| 2016-11-04 |
| 2016-11-05 |
| 2016-11-06 |
| 2016-11-07 |
| 2016-11-08 |
| 2016-11-09 |
| 2016-11-10 |
+------------+
表2
+------------+--------+----+
| dates | status | id |
+------------+--------+----+
| 2016-11-01 | 1 | 1 |
| 2016-11-02 | 1 | 1 |
| 2016-11-03 | 1 | 1 |
| 2016-11-04 | 1 | 2 |
| 2016-11-05 | 1 | 2 |
| 2016-11-06 | 1 | 2 |
| 2016-11-07 | 1 | 1 |
| 2016-11-08 | 1 | 2 |
| 2016-11-09 | 1 | 1 |
| 2016-11-10 | 1 | 1 |
+------------+--------+----+
预期结果
+------------+--------+
| dates | Status |
+------------+--------+
| 2016-11-01 | 1 |
| 2016-11-02 | 1 |
| 2016-11-03 | 1 |
| 2016-11-04 | null |
| 2016-11-05 | null |
| 2016-11-06 | null |
| 2016-11-07 | 1 |
| 2016-11-08 | null |
| 2016-11-09 | 1 |
| 2016-11-10 | 1 |
+------------+--------+
当前结果:
+------------+--------+
| dates | status |
+------------+--------+
| 2016-11-01 | 1 |
| 2016-11-02 | 1 |
| 2016-11-03 | 1 |
| 2016-11-07 | 1 |
| 2016-11-09 | 1 |
| 2016-11-10 | 1 |
+------------+--------+
这是我目前使用的查询:
select
a.dates,
b.status
from table1 a
left join table2 b on a.dates = b.dates
where b.id = 1;
不幸的是,它只显示id为1的数据并跳过空值。我也需要看到空值。我做错了什么???
答案 0 :(得分:0)
尝试:
select
a.dates,
b.status
from table1 a
left join table2 b on a.dates = b.dates AND b.id = 1
;
在您的版本中,您只获得b.id = 1
的结果答案 1 :(得分:0)
您需要将b.id = 1
条件从where
子句移动到连接条件,因为where
子句适用于连接后的整个结果集:
select
a.dates,
b.status
from table1 a
left join table2 b on a.dates = b.dates and b.id = 1