tags:

views:

159

answers:

3

Hi all,
I was wondering, is it possible to join the result of a query with itself?

(I'm using PostgreSQL)

+2  A: 

You can do so with WITH:

WITH (
    SELECT * FROM TheTable
) subquery
SELECT *
FROM subquery q1
JOIN subquery q2 on ...

Or by creating a VIEW that contains the query, and joining on that:

SELECT *
FROM TheView v1
JOIN TheView v2 on ...

Or the brute force approach: type the subquery twice:

SELECT *
FROM (
    SELECT * FROM TheTable
) sub1
LEFT JOIN (
    SELECT * FROM TheTable
) sub2 ON ...
Andomar
PostgreSQL does not support WITH queries in the latest version, 8.3, according to http://www.postgresql.org/docs/8.3/interactive/unsupported-features-sql-standard.html.
markusk
If you can upgrade to 8.4, currently in beta, WITH is finally there, see http://www.postgresql.org/docs/8.4/static/queries-with.html
Alex Martelli
Since my subquery is somewhat complex, I'll try with a view first, then the "brute force" solution.. Eventually I'll switch to using WITH when pgsql 8.4 ships :) Many thanks to everyone!
Joril
+1  A: 

Do you mean, the result of a query on a table, to that same table. If so, then Yes, it's possible... e.g.

--Bit of a contrived example but...
SELECT * 
FROM Table
INNER JOIN
(
    SELECT 
          UserID, Max(Login) as LastLogin
    FROM
          Table
    WHERE 
          UserGroup = 'SomeGroup'
    GROUP BY
          UserID

) foo
ON Table.UserID = Foo.UserID AND Table.Login = Foo.LastLogin
Eoin Campbell
Sorry, just noticed your "I'm using PostGres" comment. Not sure if the above is syntactically correct in postgres.
Eoin Campbell
It's fine AFAICS (except maybe for the 'foo' vs 'Foo' case conflict;-).
Alex Martelli
@Eoin: Well I meant joining the _results_ of the queries, but thanks for your help all the same :)
Joril
+2  A: 

Yes, just alias the queries:

SELECT  *
FROM    (
        SELECT  *
        FROM   table
        ) t1
JOIN    (
        SELECT  *
        FROM   table
        ) t2
ON      t1.column < t2.other_column
Quassnoi