关联的子查询 - Amazon Redshift
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

关联的子查询

以下示例将关联子查询 包含在 WHERE 子句中;此类型的子查询包含其列与由外部查询生成的列之间的一个或多个关联。在本示例中,关联为 where s.listid=l.listid。对于外部查询生成的每一行,将执行子查询以限定或取消限定行。

select salesid, listid, sum(pricepaid) from sales s where qtysold= (select max(numtickets) from listing l where s.listid=l.listid) group by 1,2 order by 1,2 limit 5; salesid | listid | sum --------+--------+---------- 27 | 28 | 111.00 81 | 103 | 181.00 142 | 149 | 240.00 146 | 152 | 231.00 194 | 210 | 144.00 (5 rows)

不支持的关联子查询模式

查询计划程序使用名为“子查询去相关性”的查询重写方法来优化多个关联子查询模式以便在 MPP 环境中执行。有多种类型的关联子查询采用 Amazon Redshift 无法去相关性且不支持的模式。包含以下关联引用的查询会返回错误:

  • 跳过查询块的关联引用,也称为“跨级关联引用”。例如,在以下查询中,包含关联引用的块与跳过的块由 NOT EXISTS 谓词连接:

    select event.eventname from event where not exists (select * from listing where not exists (select * from sales where event.eventid=sales.eventid));

    在本示例中,跳过的块是针对 LISTING 表执行的子查询。关联引用将 EVENT 表和 SALES 表关联起来。

  • 来自作为外部查询中 ON 子句的一部分的子查询的关联引用:

    select * from category left join event on category.catid=event.catid and eventid = (select max(eventid) from sales where sales.eventid=event.eventid);

    ON 子句包含从子查询中的 SALES 到外部查询中的 EVENT 的关联引用。

  • 针对 Amazon Redshift 系统表的 Null 敏感型关联引用。例如:

    select attrelid from stv_locks sl, pg_attribute where sl.table_id=pg_attribute.attrelid and 1 not in (select 1 from pg_opclass where sl.lock_owner = opcowner);
  • 来自包含窗口函数的子查询内部的关联引用。

    select listid, qtysold from sales s where qtysold not in (select sum(numtickets) over() from listing l where s.listid=l.listid);
  • GROUP BY 列中对关联查询结果的引用。例如:

    select listing.listid, (select count (sales.listid) from sales where sales.listid=listing.listid) as list from listing group by list, listing.listid;
  • 来自带聚合函数和 GROUP BY 子句(通过 IN 谓词连接到外部查询)的关联引用。(此限制不适用于 MIN 和 MAX 聚合函数。) 例如:

    select * from listing where listid in (select sum(qtysold) from sales where numtickets>4 group by salesid);