2013-08-02 83 views
1

我有這個問題。有n個表格動態創建,每個表格有m列,列可以重複。這些表共有2列,但它們之間沒有相關數據,例如: 表1 | A | B | Col1 | Col2 |n列表m列的SQLite聯盟

Table2 

| A | B | Col3 | Col4 |

Table3 

| A | B | Col1 | Col2 | Col4 |

我想要做的是所有表合併成一個大的一個是這樣的:

BigTable 

| A | B | Col1 | Col2 | Col3 | Col4 |

並將所有行連接起來,例如,如果在table1 rows = 5,table2 rows = 3,table3 rows = 2時,大表將有10個條目。

我可以用這樣的查詢做到這一點:

SELECT A, B, Col1, Col2, null as Col3, null as Col4 FROM Table1 
UNION 
SELECT A, B, null as Col1, null as Col2, Col3, Col4 FROM Table2 
UNION 
SELECT A, B, Col1, Col2, null as Col3, Col4 FROM Table3 

但我想知道是否有更好的方式來做到這一點,因爲會有更多的列和更多的表,並且有所有列都不同的可能性。

+0

如果table1有3行,table2有3行,那麼bigtable會有多少行? –

+0

它將有6行 –

回答

2

對您的查詢的唯一改進是使用union all而不是union。僅使用union如果明確要刪除重複的,因爲它總是嘗試:

SELECT A, B, Col1, Col2, null as Col3, null as Col4 FROM Table1 
UNION ALL 
SELECT A, B, null as Col1, null as Col2, Col3, Col4 FROM Table2 
UNION ALL 
SELECT A, B, Col1, Col2, null as Col3, Col4 FROM Table3; 

編輯:

可以進一步簡化這:

SELECT A, B, Col1, Col2, null as Col3, null as Col4 FROM Table1 
UNION ALL 
SELECT A, B, null, null, Col3, Col4 FROM Table2 
UNION ALL 
SELECT A, B, Col1, Col2, null, Col4 FROM Table3; 

列名僅用於對於union all中的第一個select。之後,這些列按位置標識。

編輯II:

有一個小竅門,你可以用它來獲得「邏輯」上union all匹配。我並不特別喜歡它,但是您不必爲所有子查詢列出列。然而,select比較複雜,而且它還有另外一個子查詢,你仍然需要子查詢:

select coalesce(t1.A, t2.A, t3.A) as A, 
     coalesce(t1.B, t2.B, t3.B) as B, 
     coalesce(t1.Col1, t2.Col1, t3.Col1) as col1, 
     coalesce(t1.Col2, t2.Col2, t3.Col2) as col2, 
     coalesce(t1.Col3, t2.Col3, t3.Col3) as col3 
from (select 'Table1' as tablename union all 
     select 'Table2' union all 
     select 'Table3' 
    ) driver left outer join 
    (select t.*, 'Table1' as tablename 
     from Table1 
    ) t1 
    on t1.tablename = driver.tablename left outer join 
    (select t.*, 'Table2' as tablename 
     from Table2 
    ) t2 
    on t2.tablename = driver.tablename left outer join 
    (select t.*, 'Table3' as tablename 
     from Table3 
    ) t3 
    on t3.tablename = driver.tablename; 
+0

不錯,所以沒有指定列的聯合所有表的方法? –

+0

我喜歡這個簡化版本,第二個看起來不錯但是很複雜,我會盡力而爲,謝謝你的幫助:) –

0

你可以這樣做(用例表來簡化),

table1是,

col1 | col2 | col3 

table2是,

col3 | col4 | col5 

現在執行工會,

select col1, col2, col3, '' as col4, '' as col5, from table1 
union 
select '' as col1, '' as col2, col3, col4, col5 from table2 

當然,當源行來自table1你會得到從列col4col5空值,併爲col1col2當源行來自table2空值。

用空值替換所需的默認值。我的例子使用空字符串,但你也可以使用0,null,無論如何。