2016-06-22 124 views
0

我有3個數據庫中的表加入有沒有共同的領域

Project    Material Used   Document 
------------  -------------------  ------------------------ 
PID | Name   MID | PID | Name   DocID | PID | Date 
------------  -------------------  ------------------------ 
1 | A    1 | 1 | A1   1  | 1 | 1/1/2016 
2 | B    2 | 1 | A1   2  | 1 | 1/2/2016 
3 | C    3 | 1 | A1   3  | 2 | 1/3/2016 
        4 | 2 | A1   4  | 2 | 1/4/2016 
        5 | 2 | A1   5  | 2 | 1/5/2016 
        6 | 3 | A1   6  | 2 | 1/6/2016 
        7 | 3 | A1   7  | 2 | 1/7/2016 
        8 | 3 | A1   8  | 1 | 1/8/2016 
        9 | 3 | A1   9  | 1 | 1/9/2016 

怎樣的結果類似下面查詢兩個或多個表?

------------------------------------------------------------------------ 
PID  Project Name MID    Material Name DocID Date 
------------------------------------------------------------------------ 
1  A    1    A1    1  1/1/2016 
1  A    2    A2    2  1/2/2016 
1  A    3    A3    NULL NULL 
2  B    4    B1    3  1/3/2016 
2  B    5    B2    4  1/4/2016 
2  B    NULL   NULL   5  1/5/2016 
2  B    NULL   NULL   6  1/6/2016 
2  B    NULL   NULL   7  1/7/2016 
3  C    6    C1    8  1/8/2016 
3  C    7    C2    9  1/9/2016 
3  C    8    C3    NULL NULL 
3  C    9    C4    NULL NULL 

PID的材料和文件表外鍵。

我正在使用Microsoft SQL 2008. 可能嗎?

+0

調整採樣數據,以使事情有點棘手,從文件中刪除一個或兩行,並添加另一個與DocId 11行。 – jarlh

+1

那些'姓名'和'日期'來自無處。你究竟想要做什麼?如果表格之間沒有關係,則無法關聯行和句點,所以我們需要繼續。 –

+0

這是不明顯的*爲什麼*結果應該是他們是。請務必在問題中解釋這一點。 – user2864740

回答

1

您似乎想要列中的列表。您可以使用full outer joinrow_number()得到這樣的:

select p.*, m.mid, m.name, d.docid, d.date 
from project p left join 
    (select m.*, row_number() over (partition by pid order by mid) as seqnum 
     from materials 
    ) m 
    on p.pid = m.pid full outer join 
    (select d.*, row_number() over (partition by pid order by docid) as seqnum 
     from documents 
    ) d 
    on p.pid = d.pid and m.seqnum = d.seqnum; 

嗯,試試這個版本:

select p.*, md.mid, md.name, md.docid, md.date 
from project p left join 
    (select m.id, m.name, d.docid, d.date 
     from (select m.*, row_number() over (partition by pid order by mid) as seqnum 
      from materials 
      ) m full outer join 
      (select d.*, row_number() over (partition by pid order by docid) as seqnum 
      from documents 
      ) d 
      on p.pid = d.pid and m.seqnum = d.seqnum 
    ) md 
    on p.pid = md.pid; 
+0

如果我使用你的查詢,如果docID行多於MID行,則p.pid總是null,反之亦然。 – Slocky