【发布时间】:2018-12-02 01:56:40
【问题描述】:
为了了解可以关联哪些类型的子查询,我编写了如下所示的 SQL 查询。它显示了我能想到的 SQL select 语句可以包含的所有类型的子查询。
虽然下面显示的示例在 Oracle 12c 中运行,但我更愿意让这个问题与数据库无关。在下面的示例中,我包含了我能想到的所有 7 种类型的子查询:
with
daily_login as ( -- 1. Independent CTE [XN]
select user_id, trunc(login_time) as day, count(*) from shopper_login
group by user_id, trunc(login_time)
),
frequent_user as ( -- 2. Dependent CTE [XN]
select user_id, count(*) as days from daily_login group by user_id
having count(*) >= 2
),
referrer (frequent_id, id, rid, ref_level) as ( -- 3. Recursive CTE [XN]
select fu.user_id, s.id, s.ref_id, 1 from frequent_user fu
join shopper s on fu.user_id = s.id
union all
select r.frequent_id, s.id, s.ref_id, r.ref_level + 1 from referrer r
join shopper s on s.id = r.rid
)
select s.id, s.name, r.id as original_referrer,
( -- 4. Scalar Subquery [CN]
select max(login_time) from shopper_login l
where l.user_id = s.id and l.success = 1
) as last_login,
m.first_login
from shopper s
join referrer r on r.frequent_id = s.id
join ( -- 5. Table Expression / Inline View / Derived Table [XN]
select user_id, min(login_time) first_login from shopper_login
where success = 1 group by user_id
) m on m.user_id = s.id
where r.rid is null
and s.id not in ( -- 6. Traditional Subquery [CN]
select user_id from persona
where description = 'Fashionista'
and id in ( -- 7. Nested subquery [CN]
select user_id from users where region = 'NORTH')
);
传说:
[C]: Can be correlated
[X]: Cannot be corretaled
[N]: Can include nested subqueries
我的问题是:
- 我得到了所有可能的类型吗?这些类型的子查询是否有替代名称?
- 我是否认为只有标量 (#4)、传统 (#6) 和嵌套 (#7) 子查询可以关联?
- 我认为表表达式和 CTE(#1、#2 和 #3)不能相关是否正确? (但是,它们可以包含可以关联的嵌套子查询)
【问题讨论】:
-
我不认为 CTE 或派生表是“子查询”。我只会区分标量子查询 (#4)、子查询 (#6) 和相关子查询(不在您的列表中)
-
@a_horse_with_no_name 我想知道这一点。你有什么我可以读到的参考资料吗?
-
还有一个在
IN子句中具有相关标量子查询的独立 CTE? -
好的,到目前为止我已经错过了:1)多个级别的嵌套子查询。 2) 相关子查询与非相关子查询组合。
标签: sql select subquery common-table-expression