H
H
hbrmdc2015-12-23 18:59:18
PostgreSQL
hbrmdc, 2015-12-23 18:59:18

How to get data from multiple related tables in Postgres?

Postgres 9.4
4 tables are linked many-to-many. I created an additional table to implement these relationships:

CREATE TABLE "public"."relation" (
      "id" uuid NOT NULL DEFAULT uuid_generate_v4(),
      "table1" uuid NOT NULL,
      "table2" uuid,
      "table3" uuid,
      "table4" uuid,
      "approved" bool DEFAULT true,
      CONSTRAINT "relation_pkey" PRIMARY KEY ("id") NOT DEFERRABLE INITIALLY IMMEDIATE,
      CONSTRAINT "table1" FOREIGN KEY ("table1") REFERENCES "public"."table1" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE,
      CONSTRAINT "table2" FOREIGN KEY ("table2") REFERENCES "public"."table2" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE,
      CONSTRAINT "table3" FOREIGN KEY ("table3") REFERENCES "public"."table3" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE,
      CONSTRAINT "table4" FOREIGN KEY ("table4") REFERENCES "public"."table4" ("id") ON UPDATE NO ACTION ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE
    )
    WITH (OIDS=FALSE);
    ALTER TABLE "public"."relation" OWNER TO "postgres";

I need to get one row from `table1` including all related rows from other tables as a JSON object.
With this code I got the rows from the `relation` table
SELECT t.*
       FROM ( SELECT table1.id,
                (select row_to_json(relations.*) as array_to_json
                  from(select * from relation where table1 = table1.id) relations
                ) as relations,
                
               from public.table1) t

But I can't figure out how to efficiently get rows from related tables using data from the `relation` table.
Perhaps this is important:
each row in the `relation` table contains two relationships - for example, with table1 and table3, the rest of the columns in this row are empty (except id, of course).
Each row in tables table1,2,3,4 contains not many links: from 1 to 10
Thank you for your time!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
romy4, 2015-12-23
@romy4

How do you not know about JOIN?
> as a JSON object.
do it on the receiving side

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question