为什么我的查询只需要1时返回4值?

时间:2016-03-04 12:48:45

标签: sql sql-server-2008

我有这个查询从表中获取值:

SELECT     
    AssemblySite, AssemblyPlannedDate, AssemblyDate, 
    ShippmentPlannedDate, ShippmentDate, DelayMotive, 
    LogisticsResponsable, HasBOM, HasSerialComponents, 
    PrototypeComponents, ReadyForAssembly, OrderPriority, DeliveryTime, 
    RequesterApproval, ApprovedDate, PlannedFinishYear, PlannedFinishWeek, 
    Designer, RawMaterial, SpecialMaterial, TestArea, DesignHours, 
    Temperature, TestType
FROM         
    Orders_Header
WHERE     
    (DVMOrderNumber = '%15078702%') 
    AND (Status = 'Completely Defined') 
    OR (Status = 'Assembly') 
    OR (Status = 'Post-Assembly') 
    OR (Status = 'Document review') 
    OR (Status = 'Delivery approval') 
    OR (Status = 'Shipping')
ORDER BY 
    AssemblyPlannedDate

我有列DVMOrderNumer,我想要一个值,更具体的是:SO-15078702。但是当我使用此查询搜索我的值时返回4值。

更具体:

SO-15078702, SO-15078703, SO-15078704, SO-15073792-08

我哪里错了?我想从我的表中得到一个值。 DVMOrderNumber有更多的统计数据,如Assembly,Post-Assembly ......

2 个答案:

答案 0 :(得分:1)

您的查询将按以下顺序执行

((DVMOrderNumber = '%15078702%') AND (Status = 'Completely Defined')) OR
  ((Status = 'Assembly') OR
  (Status = 'Post-Assembly') OR
  (Status = 'Document review') OR
  (Status = 'Delivery approval') OR
  (Status = 'Shipping'))

您需要使用正确的Parenthesis来正确过滤。试试这个子句

WHERE  ( DVMOrderNumber Like '%15078702%' )
       AND ( ( Status = 'Completely Defined' )
              OR ( Status = 'Assembly' )
              OR ( Status = 'Post-Assembly' )
              OR ( Status = 'Document review' )
              OR ( Status = 'Delivery approval' )
              OR ( Status = 'Shipping' ) ) 

或使用IN

WHERE  ( DVMOrderNumber Like '%15078702%' )
       AND Status IN ( 'Completely Defined', 'Assembly', 'Post-Assembly', 'Document review',
                       'Delivery approval', 'Shipping' ) 

答案 1 :(得分:1)

您的查询可能没有按照您想要的方式进行解析。因此,请学会使用IN

WHERE DVMOrderNumber like '%15078702%' AND 
      Status IN ('Completely Defined', 'Assembly', 'Post-Assembly', 'Document review', 'Delivery approval', 'Shipping')

您的原始查询被解析为:

WHERE (DVMOrderNumber like '%15078702%' AND Status = 'Completely Defined') OR
      (status = 'Assembly' OR
       . . .
      )

也就是说,状态仅与第一次比较的订单号相关联。当然,您可以使用括号修复原始查询,但IN是一种更干净的方法。