What is the equivalent Syntax for Outer Apply in PostgreSQL [duplicate]

橙三吉。 提交于 2020-05-26 14:29:48

问题


Im trying to find a SQL query on the equivalent usage of OUTER APPLY from MSSQL to PostgreSQL but it seems hard to find.

My MSSQL sample query is like this.

hope someone can help me with my problem. thanks in advance.

SELECT table1.col1, table1.col2, Supp.ID, Supp.Supplier

FROM SIS_PRS table1 

OUTER APPLY (SELECT TOP 1 ID, SupplierName  FROM table2 WHERE table2.ID = table1.SupplierID) AS Supp

回答1:


It is a lateral join:

SELECT table1.col1, table1.col2, Supp.ID, Supp.Supplier
FROM SIS_PRS table1 LEFT JOIN LATERAL
     (SELECT ID, SupplierName
      FROM table2
      WHERE table2.ID = table1.SupplierID
      FETCH FIRST 1 ROW ONLY
     ) Supp
     ON true;

However, you can come pretty close in either database with just a correlated subquery:

SELECT table1.col1, table1.col2, table1.SupplierID, 
       (SELECT Name
        FROM table2
        WHERE table2.ID = table1.SupplierID
        FETCH FIRST 1 ROW ONLY
       ) as SupplierName
FROM SIS_PRS table1;

Also note that in both databases, fetching one row with no ORDER BY is suspicious.



来源:https://stackoverflow.com/questions/47925994/what-is-the-equivalent-syntax-for-outer-apply-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!