How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

前端 未结 5 1968
野性不改
野性不改 2021-01-30 04:00

I am trying to write the following query on postgresql:

select name, author_id, count(1), 
    (select count(1)
    from names as n2
    where n2.id = n1.id
             


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 04:29

    I know this is old, but since Postgresql 9.3 there is an option to use a keyword "LATERAL" to use RELATED subqueries inside of JOINS, so the query from the question would look like:

    SELECT 
        name, author_id, count(*), t.total
    FROM
        names as n1
        INNER JOIN LATERAL (
            SELECT 
                count(*) as total
            FROM 
                names as n2
            WHERE 
                n2.id = n1.id
                AND n2.author_id = n1.author_id
        ) as t ON 1=1
    GROUP BY 
        n1.name, n1.author_id
    

提交回复
热议问题