2014-07-16 39 views
6

我正在使用MS SQL。
我有以下表格:無任何條件的SQL全連接

table A: 
    id1 data1 
    8234 ko 
    2  po 
    333  koo 
    40  woo 

table B: 
    id2  data2 
    123  meow 
    654  frrr 

table C: 
    id3  data3 
    10   a 
    20   b 
    30   c 
    40   d 
    50   e 
    60   f 

我想要得到這樣的:

id1  data1  id2  data2  id3  data3 
    8234 ko   123  meow  10   a 
    2  po   654  frrr  20   b 
    333  koo   NULL  NULL  30   c 
    40  woo   NULL  NULL  40   d 
    NULL NULL  NULL  NULL  50   e 
    NULL NULL  NULL  NULL  60   f 

這似乎是不附加任何條件的表的全總和。我只想從所有表中獲取所有列和所有數據。
我該怎麼做? UPD:表格不相關。
在表相關的情況下:當事先知道哪個表大於時,我會使用LEFT或RIGHT JOIN。但它是未知的。

+0

在所有相關的這些表? –

+0

@ shree.pat18,沒有。 – Alendorff

+1

@Ploutox,FULL JOIN需要加入的條件,不是嗎? – Alendorff

回答

6

使用row_number使用您的全加盟

select * from (
    select 
     row_number() over (order by id1 asc) rn, 
     id1, data1 
    from ta 
) t1  
full join (
    select 
     row_number() over (order by id2 asc) rn, 
     id2, data2 
    from tb 
) t2 on t1.rn = t2.rn 
full join (
    select 
     row_number() over (order by id3 asc) rn, 
     id3, data3 
    from tc 
) t3 on t1.rn = t3.rn 
+0

像'1,2,3'這樣的id1就是例子。我現在編輯了這篇文章。不幸的是,即使有示例,你的解決方案也不起作用,因爲第一個表比第三個小,我將從第三個表中丟失2個字符串。 :( – Alendorff

+0

但全加入工作正常:) – Alendorff

+0

和最後的條件應該是t3.rn = t1.rn或t3.rn = t2.rn – Alendorff

0

我認爲不可能在沒有匹配任何條件的情況下連接表。否則,您必須將表B中的密鑰與表A中的一個鍵一起使用。如果您不想放置表B鍵(與表A鍵匹配),則無關緊要。您仍然可以使用SQL查詢加入它。

它會像:

SELECT tableA.*, tableB.* FROMtableA JOIN tableB ON tableA.id1 = tableB.id1 

看到的,你可以根據你想選擇的領域。

+1

除了沒有通用的'id'拉。你可以做'CROSS JOIN'這樣的事情,它不需要任何條件,但是這會多次連接所有行(而不是每行只顯示一次)。 –

3

試試這個創建索引:

with a as 
(select *, row_number() over (order by id1) an from tableA), 
b as 
(select *, row_number() over (order by id2) bn from tableB), 
c as 
(select *, row_number() over (order by id3) cn from tableC) 

select a.id1, a.data1, b.id2, b.data2, c.id3, c.data3 
from a 
full outer join b on a.an = b.bn 
full outer join c on a.an = c.cn 

SQL Fiddle

+0

我們不知道哪個表具有最少的行,所以'LEFT' /'RIGHT'加入結束。 –

+0

@ Clockwork-Muse是,更改爲完全加入 –