在 JSON 个对象上加入 table
Joining table on JSON object
我有 table A,其中有 JSON 列 f
,内容如下:
[{"name": "abc", "id": "1"}, {"name": "abcd", "id": "2"}, {"name": "abcde", "id": "3"} ]
我想加入另一个 table B on id
inside JSON object described above 但也从 [=34= 获取 属性 name
] 对象。
我设法创建了以下查询:
WITH sample_data_array(arr) AS (
SELECT f FROM A
), sample_data_elements(elem) AS (
SELECT json_array_elements(arr) FROM sample_data_array
)
SELECT CAST(elem->>'id' AS int) AS id, elem->'name' AS name FROM sample_data_elements
returns 以下结果:
id, name
1, "abc"
2, "abcd"
3, "abcde"
示例数据来自 table B:
id, title, slug
1, "title 1", "title-1"
2, "title 2", "title-2"
3, "title 3", "title-3"
如何将此结果与 table B 相结合,并从所述 table 添加更多数据(列)?
预期结果:
id, name, title, slug
1, "abc", "title 1", "title-1"
2, "abcd", "title 2", "title-2"
3, "abcde", "title 3", "title-3"
SELECT
b.id,
elems ->> 'name' as name, -- 3
b.title
FROM
a,
json_array_elements(f) as elems -- 1
JOIN
b ON b.id = (elems ->> 'id')::int -- 2
- 使用
json_array_elements()
从 json 数组中取出元素
- 现在您可以加入 JSON 属性(在本例中:
id
属性作为 text
并将其转换为 int
值)
- 加入后从
b
和数组元素(如 name
)中获取所有相关值
我有 table A,其中有 JSON 列 f
,内容如下:
[{"name": "abc", "id": "1"}, {"name": "abcd", "id": "2"}, {"name": "abcde", "id": "3"} ]
我想加入另一个 table B on id
inside JSON object described above 但也从 [=34= 获取 属性 name
] 对象。
我设法创建了以下查询:
WITH sample_data_array(arr) AS (
SELECT f FROM A
), sample_data_elements(elem) AS (
SELECT json_array_elements(arr) FROM sample_data_array
)
SELECT CAST(elem->>'id' AS int) AS id, elem->'name' AS name FROM sample_data_elements
returns 以下结果:
id, name
1, "abc"
2, "abcd"
3, "abcde"
示例数据来自 table B:
id, title, slug
1, "title 1", "title-1"
2, "title 2", "title-2"
3, "title 3", "title-3"
如何将此结果与 table B 相结合,并从所述 table 添加更多数据(列)?
预期结果:
id, name, title, slug
1, "abc", "title 1", "title-1"
2, "abcd", "title 2", "title-2"
3, "abcde", "title 3", "title-3"
SELECT
b.id,
elems ->> 'name' as name, -- 3
b.title
FROM
a,
json_array_elements(f) as elems -- 1
JOIN
b ON b.id = (elems ->> 'id')::int -- 2
- 使用
json_array_elements()
从 json 数组中取出元素
- 现在您可以加入 JSON 属性(在本例中:
id
属性作为text
并将其转换为int
值) - 加入后从
b
和数组元素(如name
)中获取所有相关值