1

我有这个问题。动态创建n张表,每张表有m列,列可以重复。此表共有 2 列,但它们之间没有相关数据,例如:Table1 | 一个 | 乙| Col1 | Col2 |

    Table2

| 一个 | 乙| Col3 | Col4 |

    Table3

| 一个 | 乙| Col1 | Col2 | Col4 |

我想要做的是将所有表合并成一个这样的大表:

    BigTable

| 一个 | 乙| 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

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

4

2 回答 2

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之后,按位置标识列。

编辑二:

有一个技巧可以用来在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;
于 2013-08-02T16:54:55.147 回答
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

当然,您将从列col4col5源行来自的时间获得空值,以及源行的table1空值col1col2源行来自的时间table2

将您想要的任何默认值替换为空值。我的示例使用空字符串,但您也可以使用0,null等。

于 2013-08-02T17:34:50.520 回答