我正在尝试通过mysql左连接获取我想要的结果,但是我不能。
这是表A:
+------------+
| date |
+------------+
| 2020-04-01 |
| 2020-04-02 |
| 2020-04-03 |
| 2020-04-04 |
+------------+
表B:
+------------+----------+---------+
| date | place_id | visitor |
+------------+----------+---------+
| 2020-04-01 | 1 | 10 |
| 2020-04-02 | 1 | 12 |
| 2020-04-03 | 1 | 7 |
| 2020-04-02 | 2 | 11 |
| 2020-04-03 | 2 | 17 |
| 2020-04-04 | 2 | 21 |
+------------+----------+---------+
表C:
+----------+-------+
| place_id | place |
+----------+-------+
| 1 | A |
| 2 | B |
+----------+-------+
我想要的结果:
+------------+-------+---------+
| date | place | visitor |
+------------+-------+---------+
| 2020-04-01 | A | 10 |
| 2020-04-02 | A | 12 |
| 2020-04-03 | A | 7 |
| 2020-04-04 | A | (null) |
| 2020-04-01 | B | (null) |
| 2020-04-02 | B | 11 |
| 2020-04-03 | B | 17 |
| 2020-04-04 | B | 21 |
+------------+-------+---------+
我希望上面的最后一张表是我编写的查询的结果(A左联接B), 但它像内部联接查询一样工作。
答案 0 :(得分:1)
您可以cross join
tablea
和tablec
生成所有可能的组合,然后将tablec
与left join
一起使用:
select a.date, c.place, b.visitor
from tablea a
cross join tablec c
left join tableb b on b.place_id = c.place_id and b.date = a.date
order by a.date, c.place