代码之家  ›  专栏  ›  技术社区  ›  Hamed Kamrava

PostgreSQL空与独立表

  •  0
  • Hamed Kamrava  · 技术社区  · 6 年前

    我有一张不断增长的桌子,叫做 transactions 每月增加约1000万行。

    这张桌子有一个 jsonb 列已调用 extra .

    70%的 额外的 的列 交易 记录为空,其余记录的json值如下:

    {
       "lang": "en",
       "pages": 3,
       "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Egestas purus viverra accumsan in nisl nisi. Arcu cursus vitae congue mauris rhoncus aenean vel elit scelerisque. In egestas erat imperdiet sed euismod nisi porta lorem mollis. Morbi tristique senectus et netus. Mattis pellentesque id nibh tortor id aliquet lectus proin. Sapien faucibus et molestie ac feugiat sed lectus vestibulum..."
    }
    

    注意:全部 额外的 所有行的JSON键都是固定的,不会更改。

    概述 交易 表:

    id |  price  | type |    extra    
    -------------------------------------------
     1 | 2000.00 | SMS  |     null    
     2 | 2000.00 | SMS  |     null    
     3 | 4000.00 | SMS  |     null    
     4 | 5000.00 | SMS  | {"lang": "en", "pages":8, "message":"Lore..."}
     5 | 4000.00 | SMS  |     null    
     6 | 4000.00 | SMS  |     null    
     7 | 5000.00 | SMS  | {"lang": "de", "pages":5, "message":"Some..."}
    

    我为什么这么做?

    我在用 JSONB 列而不是三个单独的列,以避免出现许多空值。

    JSONB 我只在1列上有30%的空值,但是当我使用3个单独的列而不是1个JSONB列时,每列都有30%的空值。

    问题是:

    把我的 额外的 列成3个单独的列?

    就像这样:

    id |  price  | type | lang  | pages |  message       
    --------------------------------------------
     1 | 2000.00 | SMS  |  null |  null | null
     2 | 2000.00 | SMS  |  null |  null | null
     3 | 4000.00 | SMS  |  null |  null | null
     4 | 5000.00 | SMS  |  en   |   8   | Lorem...
     5 | 4000.00 | SMS  |  null |  null | null
     6 | 4000.00 | SMS  |  null |  null | null
     7 | 5000.00 | SMS  |  de   |   5   | Some...
    

    或者,我可以添加一个额外的表(例如 transaction_info )一对一的关系。就像这样:

    转录

    id |  price  | type
    -------------------
     1 | 2000.00 | SMS 
     2 | 2000.00 | SMS 
     3 | 4000.00 | SMS 
     4 | 5000.00 | SMS 
     5 | 4000.00 | SMS 
     6 | 4000.00 | SMS 
     7 | 5000.00 | SMS 
    

    交易信息

    id |  transaction_id  | lang  | pages |  message       
    --------------------------------------------
     1 |       4          |   en  |   8   |  Lorem...
     2 |       7          |   de  |   5   |  Some...
    

    使用这种方法,两个表上都没有任何空值。

    你喜欢哪一个?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Pavel Stehule    6 年前

    你应该阅读一些关于普通表格-1的内容。nf说-每个值都是原子的。这样一来,任何属性都有自己的列——这通常是个好主意(当属性的数量小于50时)。空值只需要1个站点,并且可能以干净的关系1nf格式存储数据比以JSON格式更有效。

    所以,因为你的新专栏只有三个,所以我对你的问题的回答是肯定的。这是个好主意。

    第二个问题一或两个表-没有明确的答复-从关系模型的角度来看,这两个变量都是正确的。如果现实中存在可见的分离-有两个实体,那么我更喜欢两个表。在其他地方(当列数很小时),我更喜欢一个表。