【问题标题】:Why subquery doesn't work in ON clause in DB2为什么子查询在 DB2 的 ON 子句中不起作用
【发布时间】:2013-01-09 04:22:51
【问题描述】:

为什么这个简单的查询在 oracle 中可以正常工作,但在 DB2 中却不行:

select * 
from 
sysibm.dual d1 
left join sysibm.dual d2 on 1=1 and exists (select 1 from sysibm.dual)

将涉及子查询的条件移动到 where 子句可能会有所帮助,但这会将外部联接限制为内部联接。

【问题讨论】:

    标签: db2 subquery on-clause


    【解决方案1】:

    当我尝试运行您的查询时,我得到一个-338 error,根据信息中心(见链接),ON 子句有以下限制:

    与 JOIN 运算符或 MERGE 语句关联的 ON 子句 由于以下原因之一而无效。

    * The ON clause cannot include any subqueries.
    * Column references in an ON clause must only reference columns
      of tables that are in the scope of the ON clause.
    * Scalar fullselects are not allowed in the expressions of an ON clause.
    * A function referenced in an ON clause of a full outer join 
      must be deterministic and have no external action.
    * A dereference operation (->) cannot be used.
    * A SQL function or SQL method cannot be used.
    * The ON clause cannot include an XMLQUERY or XMLEXISTS expression.
    

    我不确定您的查询是否可行,但您认为也许您可以重写如下内容:

    select * 
    from 
    sysibm.dual d1 
    left join (
        SELECT dl.*,
        CASE WHEN EXISTS (SELECT 1 FROM sysibm.dual)
             THEN 1
             ELSE 0
        END AS jn
        FROM sysibm.dual dl
    ) D2
      on 1=1 and 1=d2.jn
    

    【讨论】:

    • 我可以重写它,但我认为将子查询作为表加入可能会导致全扫描。我有抽象的例子:1)select * from accounts a join operations o on (o.acc_id=a.acc_id and exists (select null from operation where acc_id=o.acc_id having max(ope_date)=o.ope_date)) 2)select * from accounts a join operations o on (o.acc_id=a.acc_id) join (select max(ope_date) as ope_date,acc_id from operations group by acc_id) latestope on (latestope.acc_id=o.acc_id and latestope.ope_date=o.ope_date) 我认为第二个导致全扫描
    • 第二个查询可以写成SELECT * FROM accounts a JOIN operations o ON o.acc_id = a.acc_id WHERE o.ope_date = ( SELECT MAX(ope_date) FROM operations d WHERE o.acc_id = d.acc_id ) 如果您有一个包含o.acc_ido.ope_date 的索引,那么DB2 将使用该索引来解析MAX()。我们在$work 有一个类似的表,并且类似的查询运行得非常快。
    【解决方案2】:

    这适用于 DB2 V10.1! 没有安装补丁包。

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 2018-03-10
      • 2021-12-17
      • 2016-03-02
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多