简体   繁体   English

在数组上使用 JSONField 进行 Postgres 查询

[英]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_nametag_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中的每个namevalue ,然后使用它来匹配table_a

table_a表_a

tag_name标签名 tag_value标签值 object_uuid object_uuid
foobar富吧 coffee咖啡 aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeeeee
hello你好 world世界 3dd98cb6-978c-44b0-92fd-403032a7cb1f 3dd98cb6-978c-44b0-92fd-403032a7cb1f
key_one key_one 81bba637-4156-42b2-a2c0-ae5dd23ed695 81bba637-4156-42b2-a2c0-ae5dd23ed695

table_b表_b

id ID object_uuid object_uuid tags标签
3 3 00000000-1111-2222-3333-444444444444 00000000-1111-2222-3333-444444444444
4 4 99999999-8888-7777-6666-555555555555 99999999-8888-7777-6666-555555555555
271 271 [{"name": "foobar", "value": "coffee"}, {"name": "hello", "value": "world"}] [{“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 ID object_uuid object_uuid name姓名 value价值
271 271 foobar富吧 coffee咖啡
271 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM