0

下面是一個示例JSONB數組。我想弄清楚如何編寫一個不需要像這樣的交叉產品的查詢。有沒有更好的方式來編寫這個Postgres JSONB查詢?

select b.id from brand b,jsonb_array_elements (b.tree) a where a#>>'{Name}' = 'Skiing'; 

幫我加分

[ 
    { 
    "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 
     ] 
    } 
    },....] 

回答

1

SQL溶液中的第一翻譯這SQL鍊金:

SELECT brand.id 
FROM brand 
WHERE brand.tree @> '[{"Name": "Skiing"}]'::jsonb; 

至於sqlalchemy版本,你可以簡單地以產生SQL使用contains以上聲明:

q = (session.query(Brand.id) 
    .filter(Brand.tree.contains([{"Name": "Skiing"}])) 
    ) 
+0

甜,我錯過了外括號 – Trent

相關問題