避免“不支持这种类型的相关子查询模式”的方法
Posted
技术标签:
【中文标题】避免“不支持这种类型的相关子查询模式”的方法【英文标题】:Ways to avoid "This type of correlated subquery pattern is not supported" 【发布时间】:2017-08-08 17:58:54 【问题描述】:这就是我想要做的事情
select something1,something2,account_id,
(select u.organization_id
from public.sfdc_contact sfdcc
join public.users u on u.email=sfdcc.email
where sfdcc.account_id=account_id
group by u.organization_id
order by count(*)
limit 1
)
from something
Redshift 提示我该错误,因为我试图按计数排序。但是我不能在子查询中有 2 列,有什么提示吗?
【问题讨论】:
改用连接(编写单独的子查询并将其连接到主查询) 【参考方案1】:不完全确定此结构是否完全满足您的需求,但使用“window functions”如 ROW_NUMBER() OVER() 可用于从连接的派生表(子查询)提供单行。例如:
SELECT
s.something1
, s.something2
, s.account_id
, d2.organization_id
, d2.cn
FROM something s
LEFT JOIN (
SELECT
organization_id
, account_id
, cn
, ROW_NUMBER() OVER (PARTITION BY organization_id ORDER BY cn) rn
FROM (
SELECT
u.organization_id
, sfdcc.account_id
, COUNT(*) OVER (PARTITION BY u.organization_id, sfdcc.account_id) cn
FROM public.sfdc_contact sfdcc
JOIN public.users u ON u.email = sfdcc.email
) d1
) d2 ON s.account_id = d2.account_id and d2.rn = 1
使用 COUNT() OVER() 可能是不必要的,这可能更实用:
SELECT
s.something1
, s.something2
, s.account_id
, d2.organization_id
, d2.cn
FROM something s
LEFT JOIN (
SELECT
organization_id
, account_id
, cn
, ROW_NUMBER() OVER (PARTITION BY organization_id ORDER BY cn) rn
FROM (
SELECT
u.organization_id
, sfdcc.account_id
, COUNT(*) cn
FROM public.sfdc_contact sfdcc
JOIN public.users u ON u.email = sfdcc.email
GROUP BY
u.organization_id
, sfdcc.account_id
) d1
) d2 ON s.account_id = d2.account_id and d2.rn = 1
另请注意,如果您想要最高计数,请将 row_number 中使用的顺序更改为 DESCending:
, ROW_NUMBER() OVER (PARTITION BY organization_id ORDER BY cn DESC) rn【讨论】:
以上是关于避免“不支持这种类型的相关子查询模式”的方法的主要内容,如果未能解决你的问题,请参考以下文章