Re: [SQL] Relating 1 table to another.

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: adt09(at)dial(dot)pipex(dot)com
Cc: pgsql-sql(at)postgreSQL(dot)org
Subject: Re: [SQL] Relating 1 table to another.
Date: 1999-04-25 16:47:49
Message-ID: 10858.925058869@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"Nigel Tamplin" <adt09(at)dial(dot)pipex(dot)com> writes:
> This is ok, but to be more useful I want to show the names of the people
> so I do a
> select project.id, project.name, people.name from project,people where
> project.mainpersonid = people.id;
> That works but only shows the name of the mainperson, ok I can change it
> to show the name of the standby person instead which brings me on to my
> question...
> How can I show the names of both the main person and standby person for
> each project.

This is where you need table aliases (AS clauses). You do it like this:

select project.id, project.name, p1.name, p2.name
from project, people as p1, people as p2 where
project.mainpersonid = p1.id and project.standbypersonid = p2.id;

p1 and p2 are now independent sources of tuples --- the fact that
they're both scanning the same table is no problem.

What you'd probably really write is

select project.id, project.name,
p1.name as mainperson, p2.name as standbyperson
etc...

so that you get helpful column titles instead of just "name" twice.

regards, tom lane

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message tveith 1999-04-25 17:10:34 PL/pgsql questions..
Previous Message Tom Lane 1999-04-25 16:22:43 Re: [SQL] Confusion about DISTINCT.