Re: [SQL] Relating 1 table to another. - Mailing list pgsql-sql

From Tom Lane
Subject Re: [SQL] Relating 1 table to another.
Date
Msg-id 10858.925058869@sss.pgh.pa.us
Whole thread Raw
In response to Relating 1 table to another.  ("Nigel Tamplin" <adt09@dial.pipex.com>)
Responses Re: [SQL] Relating 1 table to another.
List pgsql-sql
"Nigel Tamplin" <adt09@dial.pipex.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


pgsql-sql by date:

Previous
From: Tom Lane
Date:
Subject: Re: [SQL] Confusion about DISTINCT.
Next
From: tveith@heaven.oeh.univie.ac.at
Date:
Subject: PL/pgsql questions..