下面是一个示例JSONB数组。我正在试图弄清楚如何编写一个不需要像这样的交叉产品的查询。
select b.id from brand b,jsonb_array_elements (b.tree) a where a#>>'{Name}' = 'Skiing';
帮助我将此翻译为SQL Alchemy的奖励积分
[
{
"Name": "Snowboarding",
"Order": 1,
"Categories": {
"Jackets": [
22002,
23224
],
"Helmets": [
24920
],
"Freestyle Boards": [
20164
],
"Goggles": [
23169,
23280
],
"Hats": [
22966,
21727
],
"Bindings": [
19265
],
"Gloves": [
20461
],
"Boots": [
26374,
19079,
21765,
22669
],
"Freeride Boards": [
18395,
25505
],
"Pants": [
24143,
20957
]
}
},
{
"Name": "Skiing",
"Order": 2,
"Categories": {
"Jackets": [
22518,
25791,
19972
],
"Pants": [
17516,
23113
],
"Goggles": [
25066,
20996
],
"Helmets": [
24378
],
"Hats": [
20009,
21245
],
"Cross-country Skiing": [
17464
],
"Gloves": [
25822
],
"Boots": [
16616
],
"Poles": [
19280
]
}
},....]
答案 0 :(得分:1)
SQL
首先解决方案:
SELECT brand.id
FROM brand
WHERE brand.tree @> '[{"Name": "Skiing"}]'::jsonb;
对于sqlalchemy
版本,您只需使用contains
即可在上方生成SQL
语句:
q = (session.query(Brand.id)
.filter(Brand.tree.contains([{"Name": "Skiing"}]))
)