2013-08-02 56 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,无论如何。