【问题标题】:alternative of left join OR condition左连接 OR 条件的替代方案
【发布时间】:2020-02-14 00:08:05
【问题描述】:

left join with or condition 会降低查询性能,所以什么可以替代 left join 或 condition

select tableb.columnA, tableb.columnB,tablec.id,tabled.id,tablee.id
from tableA tableA
LEFT JOIN tableb tableb ON ((tableb.columnA = tableA.id)
                         OR (tableb.columnB = tableA.id))

LEFT JOIN tablec tablec ON tablec.Id = tableb.columnA 
LEFT JOIN tabled tabled ON tabled.id = tableb.columnB
LEFT JOIN tablee tablee ON tablee.Id= tableb .id

【问题讨论】:

  • 为什么要涉及 tablec 和 tabled,因为你没有选择它们的任何列?
  • tableA.idtableb.columnAtableb.columbB 是否都已编入索引?我怀疑您可能会发现它们不是,因此添加 OR 条件的影响远大于应有的效果
  • @Martin 是的,所有列都已编入索引
  • @jarlh 我需要这个表格数据,但我忘了添加这个问题

标签: sql sql-server performance join left-join


【解决方案1】:

我将从在单独的joincolumnb 再次加入tableb 开始。

在其他联接中,您可以使用 ISNULL 函数,例如 tablec.Id = ISNULL(tableba.columnA, tablebb.columnA)

取决于您的需要和您的数据,您可以使用UNION/UNION ALLCOALESCEtableb 的正确实例中获取数据。

并确保tableb 中的两列都被索引覆盖。

【讨论】:

  • 但我在 tableb 左连接后使用 tableb 列到其他表进行左连接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 2021-04-21
相关资源
最近更新 更多