Re: [NOVICE] How to get n records from parent table and theirchildren
От | Lutz Horn |
---|---|
Тема | Re: [NOVICE] How to get n records from parent table and theirchildren |
Дата | |
Msg-id | 0e1d99a8-6538-8892-601a-614eecaa9fdb@posteo.de обсуждение исходный текст |
Ответ на | [NOVICE] How to get n records from parent table and their children (JORGE MALDONADO <jorgemal1960@gmail.com>) |
Список | 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 -- Sent via pgsql-novice mailing list (pgsql-novice@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-novice
В списке pgsql-novice по дате отправления: