Join tables using a value inside a JSONB column

后端 未结 1 1347
礼貌的吻别
礼貌的吻别 2021-01-01 01:57

There are two tables:

Authorized Contacts (auth_contacts):

(
userid varchar
contacts jsonb
)

contacts con

相关标签:
1条回答
  • 2021-01-01 02:27

    Proof of concept

    Your "crude way" doesn't actually work. Here is another crude way that does:

    SELECT *
    FROM  auth_contacts a
        , jsonb_to_recordset(a.contacts->'contact') AS c(contact_id text)
    JOIN  discussion d USING (contact_id);
    

    As has been commented, you can also formulate a join condition with the contains operator @>:

    SELECT *
    FROM   auth_contacts a
    JOIN   discussion d ON a.contacts->'contact'
                        @> json_build_array(json_build_object('contact_id', d.contact_id))::jsonb
    

    But rather use JSON creation functions than string concatenation. Looks cumbersome but will actually be very fast if supported with a functional jsonb_path_ops GIN index:

    CREATE INDEX auth_contacts_contacts_gin_idx ON auth_contacts
    USING  gin ((contacts->'contact') jsonb_path_ops);
    

    Details:

    • Index for finding an element in a JSON array
    • Postgres 9.4 jsonb array as table

    Proper solution

    This is all fascinating to play with, but the problem here is the relational model. Your claim:

    hence making it non JSONB type is not appropriate according as it would double or triple the amount of records.

    is the opposite of what's right. It's nonsense to wrap IDs you need for joining tables into a JSON document type. Normalize your table with a many-to-many relationship and implement all IDs you are working with inside the DB as separate columns with appropriate data type. Basics:

    • How to perform update operations on columns of type JSONB in Postgres 9.4
    • How to implement a many-to-many relationship in PostgreSQL?
    0 讨论(0)
提交回复
热议问题