我有三张桌子,如下:
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行。添加组似乎可以减少太多。
我尝试了类似下面的内容,但是连接成倍增加:
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;
答案 0 :(得分:3)
对每个表使用UNION
个连接。
SELECT p.name AS project_name, w.name AS widget_name, NULL AS sprocket_name
FROM projects AS p
INNER JOIN widgets AS w ON p.id = w.project_id
UNION ALL
SELECT p.name AS project_name, NULL AS widget_name, s.name AS sprocket_name
FROM projects AS p
INNER JOIN sprockets AS s ON p.id = s.project_id