建立sql事务关联表时出现空问题

问题描述

这是原始表格:

| country  | hostingcity |hostingembasy | statesecretary |
| -------- | ----------- | ------------ | -------------- |
| U.K.     | London      | U.S.A        | John           |
| U.K.     | London      | China        | Li             |
| U.K.     | London      | Japan        | Akira          |
| Germany  | Berlin      | U.S.A        | John           |
| Germany  | Berlin      | Austria      | Jurgen         |
| N.Korea  | null        | null         | Kim            |

大量冗余,并且给定托管使馆和国务秘书不依赖于主键国家,我们可以创建两个表:

第一张桌子:

| country  | hostingcity |
| -------  | ----------- |
| U.K.     | London      |
| Germany  | Berlin      |
| N.Korea  | null        |

第二个表:

| hostingembasy | statesecretary |
| ------------- | -------------- |
| U.S.A         | John           |
| China         | Li             |
| Japan         | Akira          |
| Austria       | Jurgen         |
| null          | Kim            |

和交易表:

| country | hostingembasy |
| ------- | ------------- |
| U.K.    |  U.S.A        |
| U.K.    |  China        |
| U.K.    |  Japan        |
| Germany |  U.S.A        |
| Germany |  Austria      |
| N.Korea |  null         |

这当然不行,因为第二张表的主键不能为空。那么当我们想要尝试和规范化表格时如何处理这种问题呢?这只是一个例子,但我可以想到很多这样的情况。估计经常看到这样的问题应该很安静吧。

解决方法

您似乎需要三个 create table 语句:

create table table1 as
    select distinct country,hostingcity
    from original;

create table table2 as
    select distinct hostingembasy statesecretary
    from original;

create table table3
    select distinct country,hostingembasy
    from original;