[英]Postgres query with JSONField on array
I am new to Postgres, and try to build a SQL query that can retrieve a Key/Value dictionary pair in an array []
from table table_b
and use it in the WHERE
clause on finding matching tag_name
and tag_value
returning the object_uuid
我是 Postgres 的新手,并尝试构建一个 SQL 查询,该查询可以从表
table_b
中检索数组[]
中的键/值字典对,并在WHERE
子句中使用它来查找匹配的tag_name
和tag_value
返回object_uuid
The original tags
on table_b
were stored as JSONField()
in Django -> Postgres and not sure how that would work in array on extracting each one out. table_b
上的原始tags
作为JSONField()
存储在 Django -> Postgres 中,不确定在提取每个标签时如何在数组中工作。
Question: How do we build a SQL query can traverse each name
and value
in table_b.tags
and then use it to match it on table_a
?问题:我们如何构建一个 SQL 查询可以遍历
table_b.tags
中的每个name
和value
,然后使用它来匹配table_a
?
table_a表_a
tag_name![]() |
tag_value![]() |
object_uuid ![]() |
---|---|---|
foobar![]() |
coffee![]() |
aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee ![]() |
hello![]() |
world![]() |
3dd98cb6-978c-44b0-92fd-403032a7cb1f ![]() |
key_one ![]() |
81bba637-4156-42b2-a2c0-ae5dd23ed695 ![]() |
table_b表_b
id ![]() |
object_uuid ![]() |
tags![]() |
---|---|---|
3 ![]() |
00000000-1111-2222-3333-444444444444 ![]() |
|
4 ![]() |
99999999-8888-7777-6666-555555555555 ![]() |
|
271 ![]() |
[{"name": "foobar", "value": "coffee"}, {"name": "hello", "value": "world"}] ![]() |
I think I come with this我想我带着这个
SELECT
id,
object_uuid,
name,
value
FROM table_b b,
jsonb_to_recordset(b.tags) AS (name TEXT, value TEXT)
id ![]() |
object_uuid ![]() |
name![]() |
value![]() |
---|---|---|---|
271 ![]() |
foobar![]() |
coffee![]() |
|
271 ![]() |
hello![]() |
world![]() |
You can join using the @>
operator after building an array with the tagname and value:在使用标记名和值构建数组后,您可以使用
@>
运算符加入:
select b.id, b.object_uuid, a.tag_name, a.tag_value
from table_b b
join table_a a on b.tags @> jsonb_build_array(jsonb_build_object('name', a.tag_name, 'value', a.tag_value));
This assumes that table_b.tags
is a jsonb
column (which it really should be).这假设
table_b.tags
是一个jsonb
列(它确实应该是)。 If it's not, you need to cast it b.tags::jsonb
如果不是,则需要将其转换为
b.tags::jsonb
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.