Thread: Relating 1 table to another.

Relating 1 table to another.

From
"Nigel Tamplin"
Date:

Attachment

Re: [SQL] Relating 1 table to another.

From
Tom Lane
Date:
"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


Re: [SQL] Relating 1 table to another.

From
Herouth Maoz
Date:
At 19:47 +0300 on 25/04/1999, Tom Lane wrote:


>
> 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;

No, AS is for field aliasing, not table aliasing.

The proper syntax is

SELECT project.id, project.name, p1.name, p2.name
FROM project, people p1, people p2
WHERE project.mainpersonid = p1.id AND project.standbypersonid = p2.id;

Herouth

--
Herouth Maoz, Internet developer.
Open University of Israel - Telem project
http://telem.openu.ac.il/~herutma