【问题标题】:PostgreSQL query rows in json object that contains certain key valuePostgreSQL 查询包含特定键值的 json 对象中的行
【发布时间】:2020-04-14 11:19:42
【问题描述】:

我有一个名为tx 的示例表,它存储有关事务的信息,并且我使用的是 PostgreSQL 10.6。

# info about my PostgreSQL version
select version()
> PostgreSQL 10.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11), 64-bit

看起来像这样:

# create table
create table tx (id bigserial primary key, msg jsonb not null);

# create index on 'type' value of msg column
create index on tx using gin ((msg->'type'));

tx 表中插入行

insert into tx (msg) values
('[{"type": "MsgSend", "value": {"amount": [{"denom": "dollar", "amount": "100"}], "from": "Jeniffer", "to": "James" }}]'),
('[{"type": "MsgSend", "value": {"amount": [{"denom": "dollar", "amount": "30"}], "from": "Jeniffer", "to": "James" }}]'),
('[{"type": "MsgBuy", "value": {"amount": [{"denom": "dollar", "amount": "10"}], "from": "George", "to": "Smith" }}]'),
('[{"type": "MsgSend", "value": {"amount": [{"denom": "dollar", "amount": "60"}], "from": "Jeniffer", "to": "James" }}]');

我已阅读此Querying JSON (JSONB) data types in PostgreSQL 并搜索了类似的帖子并使用任何给定的示例进行了测试,但它们似乎并不能很好地指导我解决我想要完成的任务,即查询json object 中的行,不是json array

这些帖子

如何实现这些查询?我相信如果我知道如何查询一个问题,那么我将能够解决其他问题。

  1. 如何查询msg列包含type的键值为MsgSend的数据?

  2. 如何查询msg列包含from的键值为Jeniffer的数据?

  3. 如何查询msg列包含MsgSend且数量为greater than 50的数据?

我将提供任何可能需要的信息来解决这个问题。

【问题讨论】:

  • 9.3 不再受支持,从那时起对 JSON 的支持有所提高。使用更新的版本。
  • 为什么将 JSON 对象包装在长度为 1 的无偿数组中?你能解决这个问题,还是不能协商?
  • @jjanes 感谢您的 cmets。这是不可协商的。看起来 Tomer Sela 在下面回复了,这是我需要知道的。

标签: sql postgresql postgresql-9.3 jsonb


【解决方案1】:

官方Postgresql documentation包含你需要的一切。

根据您的问题查看以下查询:

  1. 如何查询msg列包含的数据,键值为MsgSend的类型?
select * from tx where msg->0->>'type' = 'MsgSend';
  1. 如何查询msg列包含from的键值是Jeniffer的数据?
select * from tx where msg->0->'value'->>'from' = 'Jeniffer';
  1. 如何查询msg列包含MsgSend且数量大于50的数据?
select * from tx where (msg->0->'value'->'amount'->0->>'amount')::int > 50;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2021-03-19
    相关资源
    最近更新 更多