好吧,如果你这样做
SELECT jsonb_array_elements(summary->'users') as users FROM orders;
你得到
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ users │
├──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ {"food": [{"name": "dinner", "price": "100"}, {"name": "breakfast", "price": "50"}], "room": "2", "user": "bob"} │
│ {"room": "3", "user": "foo"} │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
让我们把这个选择放在另一个里面,选择我们需要的:
SELECT users->'user' as user_name, users->'food'->0->'name' as food FROM (
SELECT jsonb_array_elements(summary->'users') as users FROM orders
) as s;
┌───────────┬──────────┐
│ user_name │ food │
├───────────┼──────────┤
│ "bob" │ "dinner" │
│ "foo" │ (null) │
└───────────┴──────────┘
我们很接近。我们只需要添加一个WHERE
.
SELECT users->'user' as user_name, users->'food'->0->'name' as food FROM (
SELECT jsonb_array_elements(summary->'users') as users FROM orders
) as s WHERE (users->'food') is not null;
导致
┌───────────┬──────────┐
│ user_name │ food │
├───────────┼──────────┤
│ "bob" │ "dinner" │
└───────────┴──────────┘
如果您的食物阵列中有更多数据,例如
'{"users": [{"food": [{"name": "dinner", "price": "100"}, {"name" : "breakfast", "price" : "50"}], "room": "2", "user": "bob"}, {"room": "3", "user": "foo"}]}'
你可以做
SELECT users->'user' as user_name, jsonb_array_elements(users->'food')->>'name' as food FROM (
SELECT jsonb_array_elements(summary->'users') as users FROM orders
) as s WHERE (users->'food') is not null;
和
┌───────────┬───────────┐
│ user_name │ food │
├───────────┼───────────┤
│ "bob" │ dinner │
│ "bob" │ breakfast │
└───────────┴───────────┘
重写上述查询以使用公用表表达式
WITH users_data AS (
SELECT jsonb_array_elements(summary->'users') as users FROM orders
), user_food AS (
SELECT users->'user' as user_name, jsonb_array_elements(users->'food')->>'name' as food
FROM users_data
WHERE (users->'food') is not null
) SELECT * FROM user_food;
现在我们只需要分组user_name
WITH users_data AS (
SELECT jsonb_array_elements(summary->'users') as users FROM orders
), user_food AS (
SELECT users->'user' as user_name, jsonb_array_elements(users->'food')->>'name' as food
FROM users_data
WHERE (users->'food') is not null
) SELECT user_name, array_agg(food) foods FROM user_food GROUP BY user_name;
最后结果
┌───────────┬────────────────────┐
│ user_name │ foods │
├───────────┼────────────────────┤
│ "bob" │ {dinner,breakfast} │
└───────────┴────────────────────┘
这是我能想到的最好的。如果您找到更好的方法,请告诉我。