【问题标题】:SQL: Can NOT EXISTS have "OR"?SQL:不能存在有“或”吗?
【发布时间】:2020-02-19 21:54:42
【问题描述】:

我有一个不存在的 SQL 查询,用于从最终结果中排除一组特定值。

select distinct 
from [rpt_StockInventorySummary] a
where a.[DepartmentId] ='P'
and not exists (
select *
from rpt_StockInventorySummary b
where b.DepartmentId = 'p' 
and b.Manufacturer = 'warrington'
and b.LowestGroup = 57 and b.Instock = 0
and b.Barcode = a.Barcode
)
order by a.SortOrder

查询工作正常,但现在我需要修改 SQL,以便从最终结果中排除另一组值。所以我试着像这样修改NOT EXISTS里面的SQL。

select *
from rpt_StockInventorySummary b
where b.DepartmentId = 'p' 
and b.Manufacturer = 'warrington'
and (b.LowestGroup = 57 and b.Instock = 0)
or b.LowestGroup = 60
and b.Barcode = a.Barcode

查询本身运行并返回值就好了。但是当我运行整个查询时,我没有得到任何结果。我该如何解决这个问题?

【问题讨论】:

    标签: sql-server-2016 not-exists


    【解决方案1】:

    SQL 具有明确定义的操作顺序。 AND 子句在 OR 子句之前计算。因此,您的新查询将选择满足以下条件的记录:

    b.DepartmentId = 'p' 
    and b.Manufacturer = 'warrington'
    and (b.LowestGroup = 57 and b.Instock = 0)
    

    b.LowestGroup = 60
    and b.Barcode = a.Barcode
    

    我怀疑以下内容将为您提供所需的内容:

    select *
    from rpt_StockInventorySummary b
    where b.DepartmentId = 'p' 
    and b.Manufacturer = 'warrington'
    and (b.LowestGroup = 57 and b.Instock = 0 or b.LowestGroup = 60)
    and b.Barcode = a.Barcode
    

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 2018-09-30
      • 2015-01-31
      • 1970-01-01
      • 2011-10-03
      相关资源
      最近更新 更多