【问题标题】:Load Data from a denormalized table to another table - PostgreSQL11将数据从非规范化表加载到另一个表 - PostgreSQL11
【发布时间】:2019-06-13 14:07:04
【问题描述】:

我有一个包含以下列的非规范化表(比如 TableA):

TableA_Id
Cat1
Cat2
Cat3
Cat4
Cat5
Cat6

条目如下:

TableA_ID | Cat1 | Cat2 | Cat3 | Cat4 | Cat5 | Cat6
   1      |  32  |  29  | NULL | NULL | NULL | NULL
   2      |  30  |  56  | 89   | NULL | NULL | NULL
   3      |  32  |  NULL| NULL | NULL | NULL | NULL
   4      |  55  |  65  | 32   | 69   |  3   |  9

我想将它转换为另一个表(比如 TableB),其中包含唯一的关联 b/w TableA_ID 和 Cat_ID。

TableB 结构

Assoc_Id serial,
TableA_ID int,
Cat_ID    int;

而 TableB 将有关联条目(来自 TableA),例如:

Assoc_Id | TableA_ID | Cat_ID
  1      |    1      |  32
  2      |    1      |  29
  3      |    2      |  30
  4      |    2      |  56
  5      |    2      |  89
  6      |    3      |  32
  7      |    4      |  55
  8      |    4      |  65
  9      |    4      |  32
  10     |    4      |  69
  11     |    4      |  3
  12     |    4      |  9

有人可以帮忙吗?

提前致谢。

【问题讨论】:

    标签: database postgresql database-normalization postgresql-11


    【解决方案1】:

    优雅是好的,但有时简单的蛮力就足够了。特别是。应该是 1 次,或者很少执行。

    insert into TableB (TableA_id, Cat_id)
         select TableA_id, cat1 from tableA where cat1 is not null  union all
         select TableA_id, cat2 from tableA where cat2 is not null  union all
         select TableA_id, cat3 from tableA where cat3 is not null  union all
         select TableA_id, cat4 from tableA where cat4 is not null  union all
         select TableA_id, cat5 from tableA where cat5 is not null  union all
         select TableA_id, cat6 from tableA where cat6 is not null ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-09
      • 2011-03-27
      • 2017-01-23
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多