Joril
Joril

Reputation: 20547

Self-join of a subquery

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

Upvotes: 27

Views: 40630

Answers (3)

Andomar
Andomar

Reputation: 238076

You can do so with WITH:

WITH subquery AS(
    SELECT * FROM TheTable
) 
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 ...

Upvotes: 53

Quassnoi
Quassnoi

Reputation: 425361

Yes, just alias the queries:

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

Upvotes: 1

Eoin Campbell
Eoin Campbell

Reputation: 44268

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

Upvotes: 3

Related Questions