pg数据库json数据类型_科学网—如何使用PostgreSQL中的JSONB数据类型(PG JSON系列2) - 孙鹏的博文...

上一篇 使用PostgreSQL中的row_to_json()直接获得JSON(PG JSON系列1)主要针对现有的非json/jsonb类型如何输出json结果,这一篇主要写一下在数据库设计中直接使用json/jsonb数据类型(而不是json/jsonb处理函数)带来的问题。我们的问题是:设定一个典型的JSON/JSONB使用场景,以及演示如何做增删改查

There are two JSON data types: json and jsonb. They accept almost identical sets of values as input. The major practical difference is one of efficiency. The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; whilejsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed. jsonb also supports indexing, which can be a significant advantage.

Because the json type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Also, if a JSON object within the value contains the same key more than once, all the key/value pairs are kept. (The processing functions consider the last value as the operative one.) By contrast, jsonb does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys. If duplicate keys are specified in the input, only the last value is kept.

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

最后一句话很明确,基本上使用的时候,都用JSONB。原因可以这么理解json存储是纯粹字符串,jsonb的存储和访问做了解析和优化,等后面我有时间专门写一篇jsonb和json是如何在内核里实现的,以及他们到底有啥区别,此处不做纠结。

首先用JSONB来存储什么呢,我感觉和多维数组相关的比较合适,用ARRAY类型吧,输出的时候还得做个json转换,麻烦。

在数据库设计的时候,有时候为了一小件事情设置个外键关联表有点不值得,感觉有点大材小用,例如下面的演出活动的票价套餐信息(父母帮应该给我广告费,顺便也提一下我们的“两小童”):

那设计数据库的时候,就有两种方案,一种是常规的做一个关联表(TActivityPricePackage),如下图:

另外一种就是用jsonb来表示票价套餐(pricepackage),这种方法感觉到设计又简洁,还避免获取的时候做JOIN(乖乖,还能减少JAVA程序员工作,是不是也搞好了团队协作了),如下图:

为了简洁的数据库设计的理想而奋斗,下面我们来做个实验:

运行环境:PG 9.6&#x

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值