SQL Presto:不支持相关子查询
Posted
技术标签:
【中文标题】SQL Presto:不支持相关子查询【英文标题】:SQL Presto: correlated subquery is not supported 【发布时间】:2021-12-16 14:38:37 【问题描述】:考虑表x
id,val
1,100
3,300
还有表y
id
1
2
3
对于y
的每一行,我想要来自x
的val
,其中来自y 的id
是相等的,或者是最接近来自x
的id
之前的:
id,val
1,100
2,100
3,300
我试图通过相关子查询找到最接近的 id:
WITH
x AS (SELECT * FROM (VALUES (1, 100),(3, 300)) AS t(id, val)),
y AS (SELECT * FROM (VALUES 1,2,3) AS t(id))
SELECT *, (
SELECT x.id
FROM x
WHERE x.id <= y.id
ORDER BY x.id DESC
LIMIT 1
) as closest_id
FROM y
但我明白了
SYNTAX_ERROR: line 5:5: Given correlated subquery is not supported
我也尝试了左连接:
SELECT *
FROM y
LEFT JOIN x ON x.id <= (
SELECT MAX(xbis.id) FROM x AS xbis WHERE xbis.id <= y.id
)
但我得到了错误
SYNTAX_ERROR: line 7:5: Correlated subquery in given context is not supported
【问题讨论】:
【参考方案1】:您可以尝试根据小于条件加入,然后对结果进行分组,并从分组中找到需要的数据:
WITH
x AS (SELECT * FROM (VALUES (1, 100),(3, 300),(4, 400)) AS t(id, val)),
y AS (SELECT * FROM (VALUES 1,2,3,4) AS t(id))
SELECT y.id as yId,
max(x.id) as xId,
max_by(x.val, x.id) as val
FROM y
JOIN x on x.id <= y.id
GROUP BY y.id
ORDER BY y.id
输出:
yId | xId | val |
---|---|---|
1 | 1 | 100 |
2 | 1 | 100 |
3 | 3 | 300 |
4 | 4 | 400 |
【讨论】:
【参考方案2】:你这样使用我认为它的工作......
SELECT *, (
SELECT top 1 x.val
FROM x
WHERE x.id <= y.id
ORDER BY x.id DESC
) as closest_id
FROM y
【讨论】:
TOP
在 presto 中不存在,我们使用 LIMIT
代替,这不起作用
以上解决方案在 Sql server 上工作。
这是预先标记的以上是关于SQL Presto:不支持相关子查询的主要内容,如果未能解决你的问题,请参考以下文章