Re: How to get n records from parent table and their children

From: Lutz Horn <lutz(dot)horn(at)posteo(dot)de>
To: pgsql-novice(at)postgresql(dot)org
Subject: Re: How to get n records from parent table and their children
Date: 2017-11-15 19:51:39
Message-ID: 0e1d99a8-6538-8892-601a-614eecaa9fdb@posteo.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Hi,

Am 15.11.17 um 20:14 schrieb JORGE MALDONADO:
> I have a parent and child tables and need to get "n" records from
> parent table and all of the records in child for such "n" records in
> parent.
Do you have tables like this?

utz=> \d parent
Table "pg_temp_3.parent"
Column | Type | Modifiers
--------+---------+-----------------------------------------------------
id | integer | not null default nextval('parent_id_seq'::regclass)
name | text |
Indexes:
"parent_pkey" PRIMARY KEY, btree (id)
Referenced by:
TABLE "child" CONSTRAINT "child_parent_id_fkey" FOREIGN KEY
(parent_id) REFERENCES parent(id)

lutz=> \d child
Table "pg_temp_3.child"
Column | Type | Modifiers
-----------+---------+----------------------------------------------------
id | integer | not null default nextval('child_id_seq'::regclass)
name | text |
parent_id | integer |
Indexes:
"child_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"child_parent_id_fkey" FOREIGN KEY (parent_id) REFERENCES parent(id)

lutz=> select * from parent;
id | name
----+------
1 | foo
2 | bar
3 | baz
(3 rows)

lutz=> select * from child;
id | name | parent_id
----+-------------+-----------
1 | foo-child-1 | 1
2 | foo-child-2 | 1
3 | bar-child-1 | 2
4 | baz-child-1 | 3
(4 rows)

If you now want to select all "child" rows that have parent in a limited
set, you can use a subquery
(https://www.postgresql.org/docs/current/static/functions-subquery.html)

lutz=> select * from child where parent_id in (
select id from parent limit 2
);
id | name | parent_id
----+-------------+-----------
1 | foo-child-1 | 1
2 | foo-child-2 | 1
3 | bar-child-1 | 2
(3 rows)

Lutz

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message john snow 2017-11-16 03:53:39 group by rollup and cube
Previous Message JORGE MALDONADO 2017-11-15 19:14:01 How to get n records from parent table and their children