Re: join question - three tables, two with foreign keys to

From: Stephan Szabo <sszabo(at)megazone23(dot)bigpanda(dot)com>
To: Dmitri Colebatch <dim(at)bigpond(dot)net(dot)au>
Cc: <pgsql-sql(at)postgresql(dot)org>
Subject: Re: join question - three tables, two with foreign keys to
Date: 2002-06-13 15:21:28
Message-ID: 20020613081443.A4208-100000@megazone23.bigpanda.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


On Fri, 14 Jun 2002, Dmitri Colebatch wrote:

> maybe just to qualify, I get this:
>
> select emp.name, lv.from_date, lv.to_date, pay.amount
> from employee as emp
> left join employee_leave as lv on emp.id = lv.employee_id
> left join employee_pay as pay on emp.id = pay.employee_id
> where emp.id = 1;
>
> name | from_date | to_date | amount
> ------+------------+------------+--------
> dim | 2002-10-05 | 2002-05-14 | 100
> dim | 2002-10-05 | 2002-05-14 | 100
> dim | 2002-10-06 | 2002-06-14 | 100
> dim | 2002-10-06 | 2002-06-14 | 100
> (4 rows)
>
> but would expect the results to be
>
> name | from_date | to_date | amount
> ------+------------+------------+--------
> dim | 2002-10-05 | 2002-05-14 | (null)
> dim | 2002-10-05 | 2002-05-14 | (null)
> dim | (null) | (null) | 100
> dim | (null) | (null) | 100
> (4 rows)
>
> am I missing something?

I don't see why you'd expect that.
Both rows in employee_leave match and both rows
in employee_pay match. They're not unrelated joins,
you're asking to join employee with employee_leave
and then join the results of that with employee_pay.

Perhaps you want a union? Something like:
select emp.name, lv.from_date, lv.to_date, null as amount
from employee as emp, employee_leave as lv where emp.id=
lv.employee_id
union
select emp.name, null, null, pay.amount
from employee as emp, employee_pay as pay where emp.id=
pay.employee_id

If you want to get a row for an employee even when they
have neither leave nor pay, you can use left joins above,
but that'll give you some rows that'll be like
<name> NULL NULL NULL.

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message joseph 2002-06-13 15:59:12 how do i provide array parameters for my functions in php
Previous Message Manfred Koizar 2002-06-13 15:19:08 Re: join question - three tables, two with foreign keys to the first