如何在sql server中替换联接中的OR语句

如何在sql server中替换联接中的OR语句,sql,tsql,Sql,Tsql,我有一个对连接使用or语句的查询,所以基本上如果连接上的一个条件不满足,它必须检查下一个条件。问题是,使用OR语句需要很长时间才能运行,但当我删除其中一个OR条件时,它会立即运行。有没有更好的方法可以在不使用OR语句的情况下同时使用这两个条件来执行此操作,从而加快查询速度 select t5.TransactionNumber ,t4.ID ,t3.[Entry] AS Amount ,t2.Address AS AddressDetail

我有一个对连接使用or语句的查询,所以基本上如果连接上的一个条件不满足,它必须检查下一个条件。问题是,使用OR语句需要很长时间才能运行,但当我删除其中一个OR条件时,它会立即运行。有没有更好的方法可以在不使用OR语句的情况下同时使用这两个条件来执行此操作,从而加快查询速度

  select t5.TransactionNumber
        ,t4.ID
        ,t3.[Entry] AS Amount 
        ,t2.Address AS AddressDetail
        ,t1.PhoneNumber   AS  ContactNumber
  FROM Table1 t1 (NOLOCK)
  JOIN Table2 t2 (NOLOCK) ON t2.FicaID = t1.FicaId 
  inner  join Table3 t3 (NOLOCK) ON (t3.ID = t2.ID AND t3.Code = t2.Code) or (t3.TypeID = t2.TypeID)  //on this join i have an or statement if one condition isnt met it must check the next condition
  LEFT JOIN Table4 t4 (NOLOCK) ON t4.Result = t3.Result
  LEFT JOIN Table5 t5 (NOLOCK) ON t5.AccNum = t3.AccNum
  where t1.date>'2018-09-01' and t1.date<'2018-09-30'

您可以尝试以下查询:

 select * from
 (
  select t5.TransactionNumber
        ,t4.ID
        ,t3.[Entry] AS Amount 
        ,t2.Address AS AddressDetail
        ,t1.PhoneNumber   AS  ContactNumber
         FROM Table1 t1 (NOLOCK)
        JOIN Table2 t2 (NOLOCK) ON t2.FicaID = t1.FicaId 
        inner  join Table3 t3 (NOLOCK) ON (t3.ID = t2.ID AND t3.Code = t2.Code)
        )A
         join Table3 t3 (NOLOCK) ON (A.TypeID = t3.TypeID)   

        LEFT JOIN Table4 t4 (NOLOCK) ON t4.Result = t3.Result
        LEFT JOIN Table5 t5 (NOLOCK) ON t5.AccNum = t3.AccNum
        where t1.date>'2018-09-01' and t1.date<'2018-09-30'

您可以尝试使用左连接和合并函数

select t5.TransactionNumber
        ,t4.ID
        ,COALESCE(t3.[Entry],t33.[Entry]) AS Amount 
        ,t2.Address AS AddressDetail
        ,t1.PhoneNumber   AS  ContactNumber
  FROM Table1 t1 (NOLOCK)
  JOIN Table2 t2 (NOLOCK) ON t2.FicaID = t1.FicaId 
  left  join Table3 t3 (NOLOCK) ON (t3.ID = t2.ID AND t3.Code = t2.Code)
  left join Table3 t33  (t33.TypeID = t2.TypeID)  //I moved it to left join
  LEFT JOIN Table4 t4 (NOLOCK) ON t4.Result = t3.Result
  LEFT JOIN Table5 t5 (NOLOCK) ON t5.AccNum = t3.AccNum
  where t1.date>'2018-09-01' and t1.date<'2018-09-30'

根据逻辑上的分布规律

p或Q和R可以写成
P或Q和P或R。。也许这会有帮助?

您可以将or条件放在where子句中,并可能在这些列上创建索引。@AnkitBajpai那么我将如何连接到该表上?连接条件和where条件的工作方式类似。它们都用来过滤行。我试过了,但它忽略了另一个条件,它只读取第一个条件,不读取另一个条件。例如,如果这两个条件都返回true,它将无法检测both@john或者,如果第一个条件满足,那么就不需要第二个条件,那么如果第一个条件不满足,那么它将尝试第二个条件?@john当然会,因为如果是第一个条件,那么它将从中获取数据,因为联合函数获取第一个非空值我只是快速浏览了一个测试的条件,它仍然没有返回任何信息,但是有数据,因为当我运行查询时,它返回的是以前的信息,这表示表2不能绑定