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
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.
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?
table_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
| 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:This assumes that
table_b.tagsis ajsonbcolumn (which it really should be). If it's not, you need to cast itb.tags::jsonb