What is the difference between LATERAL and a subquery in PostgreSQL?

后端 未结 4 1088
花落未央
花落未央 2020-11-21 08:58

Since Postgres came out with the ability to do LATERAL joins, I\'ve been reading up on it, since I currently do complex data dumps for my team with lots of inef

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 09:04

    First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

    Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

    Consider following query.

    Select A.*
    , (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
    , (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
    FROM A 
    

    You can use lateral in this condition.

    Select A.*
    , x.Column1
    , x.Column2
    FROM A LEFT JOIN LATERAL (
      Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
    ) x ON X.Fk1 = A.PK
    

    In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

    There are more usages for lateral or cross apply but this is most common one I found.

提交回复
热议问题