具有m列的n个表的SQLite联合

时间:2013-08-02 16:44:37

标签: android sql android-sqlite

我有这个问题。有动态创建的n个表,每个表有m列,可以重复列。这些表共有2列,但它们之间没有相关数据,例如:         表格1 | A | B | Col1 | Col2 |

    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,则big table将有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

但我想知道是否有更好的方法可以做到这一点,因为会有更多的列和更多的表,并且所有列都有可能不同。

2 个答案:

答案 0 :(得分:3)

您的查询的唯一改进是使用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;

列名仅用于select中的第一个union all。之后,列由位置标识。

编辑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;

答案 1 :(得分: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

当然,当源行来自col4时,您会从列col5table1获取空值,col1和{的值为空{1}}来源行来自col2

替换空值所需的任何默认值。我的示例使用空字符串,但您也可以使用table20,无论如何。