2016-02-24 23 views
0

我有4臺這樣的PostgreSQL的 - 在聲明中有一個表從許多不同的

table a: 

art_id | name | surname 
-------+-------+-------- 
    1 | John | McA 
    2 | Alex | McB 
    3 | Juddy | McC 

table b: 
art_id is a foreign key to table a 
diff_id is foreign key to table c 

art_id | title | diff_id 
-------+-------+-------- 
    1 | smth | 1.1 
    2 | else | 1.2 
    3 | here | 1.3 

table c: 
class is foreign key to table d 

class | date | diff_id 
-------+-------+-------- 
    a | 01.02 | 1.1 
    b | 02.03 | 1.2 
    c | 03.04 | 1.3 

table d: 

class | deputy| 
-------+-------+ 
    a | John | 
    b | Marc | 
    c | Sophie| 

我想寫一個postresql語句有這樣一個表:

table result: 

| title | deputy | 
+-------+--------+ 
| smth | John | 
| else | Marc | 
| here | Sophie | 

我我試圖通過WITH AS statement bun來做到這一點,因爲我被卡住了。 在聲明中創建遞歸表後,我試圖通過執行LEFT JOIN語句來解決該問題,但它將結果表中的記錄相乘。

謝謝你的幫忙!

+0

爲什麼你需要WITH或遞歸? b,c和d之間不會有簡單的連接嗎? –

+0

我沒有嘗試過。我需要爲特定的art_id收集diff_id,存儲diff_id以從表c中獲取類,並將該類存儲爲最終從表d獲取副本。如果你知道如何做得更快,更容易隨時給我一個建議:)! – axeMaltesse

+0

'選擇b.art_id,d.deputy從b連接c上b.diff_id = c.diff_id連接d上c.class = d.class'浮現在腦海中 –

回答

2

我認爲你已經完成了遞歸查詢和存儲即時值的任務。我相信簡單的JOIN就足夠你想要實現的。

SELECT 
    b.title, d.deputy 
FROM 
    b 
    INNER JOIN c ON b.diff_id = c.diff_id 
    INNER JOIN d ON c.class = d.class 

如果需要標題,當有在副列中沒有匹配值顯示,比你可能需要改變INNERLEFT連接類型。

此外,如果您收到多個結果一title與正好在deputy列中的值相同考慮增加一個DISTINCT條款:

SELECT DISTINCT 
    b.title, d.deputy 
FROM 
    b 
    INNER JOIN c ON b.diff_id = c.diff_id 
    INNER JOIN d ON c.class = d.class 

如果你真的覺得有必要包括表a然後重寫查詢:

SELECT 
    b.title, d.deputy 
FROM 
    a 
    INNER JOIN b ON a.art_id = b.art_id 
    INNER JOIN c ON b.diff_id = c.diff_id 
    INNER JOIN d ON c.class = d.class 
+0

謝謝。用我的WITH AS語句使用解決方案的第三部分,它可以工作。 它比我描述的更復雜,所以我不得不使用遞歸查詢從多行中選擇diff_id,方法是使用art_id分別捕獲它們。 謝謝你的幫助! – axeMaltesse

相關問題