Snowflake (LEFT JOIN) LATERAL: Unsupported subquery type cannot be evaluated

旧时模样 提交于 2021-01-24 08:10:38

问题


Lateral Join

In a FROM clause, the LATERAL keyword allows an in-line view to reference columns from a table expression that precedes that in-line view.

A lateral join behaves more like a correlated subquery than like most JOINs.

Let's tweak the code provided in documentation a bit:

CREATE TABLE departments (department_id INTEGER, name VARCHAR);
CREATE TABLE employees (employee_ID INTEGER, last_name VARCHAR,
                        department_ID INTEGER, project_names ARRAY);

INSERT INTO departments (department_ID, name) VALUES 
    (1, 'Engineering'), 
    (2, 'Support'),
    (3, 'HR');  -- adding new row

INSERT INTO employees (employee_ID, last_name, department_ID) VALUES 
    (101, 'Richards', 1),
    (102, 'Paulson',  1),
    (103, 'Johnson',  2);  

Query:

SELECT * 
FROM departments AS d,
LATERAL (SELECT * FROM employees AS e 
         WHERE e.department_ID = d.department_ID 
         ORDER BY employee_id DESC LIMIT 1) AS iv2  -- adding ORDER BY ... LIMIT ...
ORDER BY employee_ID;

SQL compilation error: Unsupported subquery type cannot be evaluated

Yes, I am aware I could rewrite this query with ROW_NUMBER() or other ways.


1) Why the usage of TOP/LIMIT is not possible in this particular scenario?

2) Is there a syntax to achieve LEFT JOIN LATERAL/OUTER APPLY?

I would like to be able too get all source rows in the resultset even if the LATERAL subquery produces no rows for them. To get as final result:

┌────────────────┬──────────────┬──────────────┬────────────┬────────────────┬───────────────┐
│ department_id  │    name      │ employee_id  │ last_name  │ department_id  │ project_names │
├────────────────┼──────────────┼──────────────┼────────────┼────────────────┼───────────────┤
│             1  │ Engineering  │ 102          │ Paulson    │ 1              │ null          │
│             2  │ Support      │ 103          │ Johnson    │ 2              │ null          │
│             3  │ HR           │ null         │ null       │ null           │ null          │
└────────────────┴──────────────┴──────────────┴────────────┴────────────────┴───────────────┘

db<>fiddle demo

来源:https://stackoverflow.com/questions/60477157/snowflake-left-join-lateral-unsupported-subquery-type-cannot-be-evaluated

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