Self-join of a subquery

前端 未结 3 1262
慢半拍i
慢半拍i 2021-02-04 02:53

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

3条回答
  •  悲哀的现实
    2021-02-04 02:59

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

提交回复
热议问题