JOINing subselects in FROM? - Mailing list pgsql-general

From Alvaro Herrera
Subject JOINing subselects in FROM?
Date
Msg-id 20020410012717.74771ff9.alvherre@atentus.com
Whole thread Raw
Responses Re: JOINing subselects in FROM?  (Tom Lane <tgl@sss.pgh.pa.us>)
Re: JOINing subselects in FROM?  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-general
Hello:

I'm playing around with the syntax of the SELECT.

I have a very simple table (this is a silly example):

create table datos (año int, mes text, valor int);

with a couple tuples:

insert into datos (año, mes, valor) values (1999, 'enero', 100);
insert into datos (año, mes, valor) values (2000, 'enero', 200);
insert into datos (año, mes, valor) values (1999, 'febrero', 300);

I'm trying to JOIN two subselects-in-from clauses and can't get it
right:

SELECT foo1.mes, valor1999 AS "1999", valor2000 AS "2000" FROM
    (SELECT valor AS valor1999, mes FROM datos WHERE año=1999) AS foo1
    OUTER JOIN
        (SELECT valor AS valor2000, mes FROM datos WHERE año=2000) AS foo2
    ON foo1.mes=foo2.mes;
ERROR:  parser: parse error at or near "OUTER"

If I try to do an INNER JOIN, I get instead
SELECT foo1.mes, valor1999 AS "1999", valor2000 AS "2000" FROM
    (SELECT valor AS valor1999, mes FROM datos WHERE año=1999) AS foo1
    INNER JOIN
        (SELECT valor AS valor2000, mes FROM datos WHERE año=2000) AS foo2
    ON foo1.mes=foo2.mes;
ERROR:  flatten_join_alias_var: unexpected subtree type

But if I do it like
SELECT foo1.mes, valor1999 AS "1999", valor2000 AS "2000" FROM
        (SELECT valor AS valor1999, mes FROM datos WHERE año=1999) AS foo1,
        (SELECT valor AS valor2000, mes FROM datos WHERE año=2000) AS foo2
  WHERE foo1.mes=foo2.mes;

it works (but I lose some tuples -- I expected to get NULL there in the
OUTER JOIN query).


Remember, this is a silly example, I'm not trying to use it for anything
but playing around with the syntax. But I wonder whether this is
supposed to work?

alvherre=> select version();
                            version
----------------------------------------------------------------
 PostgreSQL 7.3devel on i686-pc-linux-gnu, compiled by GCC 2.96
(1 row)


On a related note, psql's "\h select" shows the syntax for select, but
it doesn't specify what are the terminal symbols for the join_type
non-terminal.

(this is a week-old or so CVS)

--
Alvaro Herrera (<alvherre[a]atentus.com>)
"Puedes vivir solo una vez, pero si lo haces bien, una vez es suficiente"

pgsql-general by date:

Previous
From: Lamar Owen
Date:
Subject: Re: Problems building 7.2.1 RPMs
Next
From: Devrim GUNDUZ
Date:
Subject: Who's using PostgreSQL? (thanks)