[英]PostgreSQL query rows in json object that contains certain key value
我有一個名為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" }}]');
我已經在 PostgreSQL 中閱讀了這個查詢 JSON (JSONB) 數據類型並搜索了類似的帖子並使用任何給定的示例進行了測試,但它們似乎並沒有很好地指導我解決我想要完成的任務,即在json object
查詢行json object
,而不是json array
這些帖子
我如何去實現這些查詢? 我相信如果我知道如何查詢一個,那么我就能解決其他問題。
如何查詢msg
列包含type
鍵值為MsgSend
?
如何查詢msg
列包含的數據,其中from
鍵值是Jeniffer
?
如何查詢msg
列包含MsgSend
且數量greater than 50
?
我將提供解決此問題可能需要的任何信息。
官方Postgresql 文檔包含您需要的一切。
根據您的問題查看以下查詢:
- 如何查詢 msg 列包含類型鍵值為 MsgSend 的數據?
select * from tx where msg->0->>'type' = 'MsgSend';
- 如何查詢 msg 列包含的數據,其中 from 的鍵值是 Jeniffer?
select * from tx where msg->0->'value'->>'from' = 'Jeniffer';
- 如何查詢 msg 列包含 MsgSend 且數量大於 50 的數據?
select * from tx where (msg->0->'value'->'amount'->0->>'amount')::int > 50;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.