[英]How to create table-like structure in json
I need to put below 'table' into a json, where values would be as easily accessible as from table.我需要将“表”下方放入 json 中,其中的值与从表中一样容易访问。 Here's the small sample and simple example query of usage.这是使用的小样本和简单示例查询。
with prizes as (
select t.stake, tickets_no, t.prize
from (values
(400, 5, 10)
, (1000, 10, 25)
, (2000, 50, 70)
) t
(stake, tickets_no, prize)
order by 1,2
)
select max(prize) from prizes
where 1200 >= stake
and 27 >= tickets_no
I want to put it in some kind of this structure:我想把它放在某种这样的结构中:
https://www.db-fiddle.com/f/pS5vR4CM8Y6sjsVXkw7XUY/1 https://www.db-fiddle.com/f/pS5vR4CM8Y6sjsVXkw7XUY/1
create table promotions
(id integer,
details jsonb);
insert into promotions
values
(1, '{"name": "promo1", "rules":[/* it should be an array here or somehow different? */]}');
It could be simpler if you reorganize your JSON structure a bit:如果你重新组织你的 JSON 结构可能会更简单:
insert into promotions
values
(1, '{"name":"promo1","rules":[{"stake":100,"tickets_no":10,"prize":200},{"stake":500,"tickets_no":30,"prize":700},{"stake":1000,"tickets_no":80,"prize":1200}]}');
create type t_rule as (prize int, stake int, tickets_no int);
select id, t.*
from promotions, jsonb_populate_recordset(null::t_rule, details->'rules') as t;
id | prize | stake | tickets_no
----+-------+-------+------------
1 | 200 | 100 | 10
1 | 700 | 500 | 30
1 | 1200 | 1000 | 80
select max(prize)
from promotions, jsonb_populate_recordset(null::t_rule, details->'rules') as t
where stake < 1111;
max
------
1200
I managed to do this:我设法做到了:
create table promotions
(id integer,
details jsonb);
insert into promotions
values
(1, '{"name": "promo1", "rules":{"stake":[100,500,1000], "tickets_no":[10,30,80], "prize":[200,700, 1300]}
}');
+ simple query with operation of values:
with promo as (select jsonb_array_elements(details -> 'rules' -> 'stake')::text::integer as stake,
jsonb_array_elements(details -> 'rules' -> 'tickets_no')::text::integer as bets_no,
jsonb_array_elements(details -> 'rules' -> 'prize')::text::integer as prize
from promotions )
select max(prize) from promo where 1111 > stake
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.