【发布时间】:2017-11-18 00:33:45
【问题描述】:
我有三个表,如下所示:
projects
| id | name |
|----|------------|
| 1 | enterprise |
| 2 | discovery |
widgets
| project_id | name |
|------------|-----------------|
| 1 | saucer section |
| 1 | pylons |
| 2 | spinning saucer |
| 2 | angular pylons |
sprockets
| project_id | name |
|------------|-------------|
| 1 | engineering |
| 1 | bridge |
| 1 | mess |
| 2 | engineering |
| 2 | bridge |
| 2 | mess |
我要写的是一个查询,它给我正好十个结果:基本上是widgets 和sprockets 中的每一行一个,看起来像这样:
result
| project_name | widget_name | sprocket_name |
|--------------|-----------------|---------------|
| enterprise | saucer section | null |
| enterprise | pylons | null |
| enterprise | null | engineering |
| enterprise | null | bridge |
| enterprise | null | mess |
| discovery | spinning saucer | null |
| discovery | angular pylons | null |
| discovery | null | engineering |
| discovery | null | bridge |
| discovery | null | mess |
相反,我的联接合并返回 12 行。添加 group by 似乎减少了太多。
我尝试了类似以下的方法,但连接数成倍增加:
select
p.name as project_name,
w.name as widget_name,
s.name as sprocket_name
from
projects as p
left join widgets w on p.id = w.project_id
left join sprockets s on p.id = s.project_id;
answersI'vefound 主要专注于重新设计数据库,但这不是我的选择。 如何编写一个连接以从该数据集中返回上述十行?
【问题讨论】: