2017-11-18 194 views
0

我有三個表,就像這樣:加入一個表,兩個獨立的一個一對多表

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  | 

我想寫的是,給我正好十個結果的查詢:基本上是一個爲每行widgetssprockets,看起來像這樣:

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; 

answersI'vefound主要集中在重新設計的數據庫,但是這不是我的選擇。 如何編寫連接以從此數據集返回上述十行?

回答

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 
+0

這樣做的結果是20行,其中一些數據看起來與我想要的不相關。我錯過了什麼嗎? –

+1

糟糕,忘記了'ON'子句 – Barmar

+0

如果您將「p」添加到「FROM projects AS p」的第二行,我會接受這個答案:) –

相關問題