Re: select on many-to-many relationship

From: Виктор Егоров <vyegorov(at)gmail(dot)com>
To: ssylla <stefansylla(at)gmx(dot)de>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: select on many-to-many relationship
Date: 2012-11-27 17:48:22
Message-ID: CAGnEbojoGAVzJtpjFFtowPifdbjVKn6DELt6D8gy96x72JOTQQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

2012/11/27 ssylla <stefansylla(at)gmx(dot)de>:
> assuming I have the following n:n relationship:
>
> intermediary table:
> t3
> id_project|id_product
> 1|1
> 1|2
> 2|1
>
> How can I create an output like this:
> id_project|id_product1|id_product2
> 1|1|2
> 2|1|NULL

I'd said the sample is too simplified — not clear which id_product
should be picked if there're more then 2 exists.
I assumed the ones with smallest IDs.

-- this is just a sample source generator
WITH t3(id_project, id_product) AS (VALUES (1,1),(1,2),(2,1))
-- this is the query
SELECT l.id_project, min(l.id_product) id_product1, min(r.id_product)
id_product2
FROM t3 l
LEFT JOIN t3 r ON l.id_project=r.id_project AND l.id_product < r.id_product
GROUP BY l.id_project;

--
Victor Y. Yegorov

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Sergey Konoplev 2012-11-28 00:27:21 Re: select on many-to-many relationship
Previous Message David Johnston 2012-11-27 14:22:08 Re: Using regexp_matches in the WHERE clause