有多少种SQL子查询?

时间:2018-06-22 14:45:00

标签: sql select subquery common-table-expression

为了理解可以关联哪些类型的子查询,我编写了如下所示的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)不能相互关联? (但是,它们可以包含可以关联的嵌套子查询)

1 个答案:

答案 0 :(得分:1)

相关子查询:

const apiHeaders = new HttpHeaders({ 'Content-Type': 'application/json',
 'Cache-control': 'no-cache, no-store, must-revalidate',
 'Pragma': 'no-cache',
 'Expires': '-1'
 });

...
...
return this.http.get(uri, { headers: apiHeaders}):
...