【问题标题】:Analog of OUTER APPLY in other RDBMS (not SQL Server)其他 RDBMS(不是 SQL Server)中的 OUTER APPLY 的模拟
【发布时间】:2013-05-31 20:55:24
【问题描述】:

我在工作中使用 SQL Server,并且我有一些 OUTER APPLY 子句的好技巧,可以帮助我不重复代码。例如,如果我有一个这样的表:

create table Transactions
(
    ID bigint identity(1, 1) primary key, [Date] datetime, Amount decimal(29, 2), Amount2 decimal(29, 2)
)

insert into Transactions ([Date], Amount, Amount2)
select getdate(), 100.00, null union all
select getdate(), 25.00, 75.00

我想从中选择数据,例如我将为每个不为空的金额设置一行,我可以这样查询:

select
  T.ID,
  T.[Date],
  OA.Amount
from Transactions as T
  outer apply (
      select T.Amount as Amount union all
      select T.Amount2 as Amount
  ) as OA
where OA.Amount is not null

而不是使用union:

select
  T.ID,
  T.[Date],
  T.Amount
from Transactions as T
where T.Amount is not null

union all

select
  T.ID,
  T.[Date],
  T.Amount2 as Amount
from Transactions as T
where T.Amount2 is not null

所以我想知道 - 其他 RDBMS 是否有这种可能性?

SQL FIDDLE

【问题讨论】:

  • PostgreSQL 9.3 将具有LATERAL,这是 SQL Server 的 outer apply 的 ANSI 等效项
  • 谢谢,所以有 ANSI 等价物:)
  • 手册中有一些例子:postgresql.org/docs/9.3/static/…

标签: mysql sql sql-server oracle postgresql


【解决方案1】:

在 Oracle 中,横向连接是一种笛卡尔连接,其结果集取决于行的值。尚未引入新关键字 (SQLFiddle):

SQL> CREATE OR REPLACE TYPE number_nt AS TABLE OF NUMBER;
  2  /

Type created
SQL> SELECT t.id, t.dt, u.column_value amount
  2    FROM Transactions t
  3   CROSS JOIN TABLE(number_nt(t.amount, t.amount2)) u;

        ID DT                AMOUNT
---------- ----------- ------------
         1 05/06/2013           100
         1 05/06/2013  
         2 05/06/2013            25
         2 05/06/2013            75

不过,Oracle 似乎使用了 LATERAL 关键字 internally

【讨论】:

  • 标准的LATERAL 连接不一定是CROSS JOIN。在此处查看一些示例:postgresql.org/docs/9.3/static/…
  • @a_horse_with_no_name 此链接列出了横向连接的三种用途:标准连接、交叉连接和外部交叉连接,所有这些都可以重写为具有依赖结果集的笛卡尔积。
  • 你看到... LEFT JOIN LATERAL ...了吗?
  • @a_horse_with_no_name 你可以做一个external cross join =) 虽然我同意 LATERAL 运算符更方便和优雅,而且我感觉它将在未来的 Oracle 版本中引入,因为显然它内部使用。
猜你喜欢
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 2022-12-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多