【问题标题】:Using multiple conditions in where clause of SQL Server在 SQL Server 的 where 子句中使用多个条件
【发布时间】:2019-03-01 03:33:15
【问题描述】:

我的数据库中有一个名为finalres 的表,其中包含状态和帐户列表。

我想拉取状态不应该在的账户:

(xxx, ina, nfc)

我还想提取状态在RWD 中的帐户,但前提是帐户# 为空。我写了下面的查询,但它只给出任一条件的结果。请帮帮我。

select *
from finalres
where 1 = 0
   or (status = 'rwd' and account# is null)
   or status not in ('xxx', 'ina', 'nfc')

【问题讨论】:

  • 请编辑您的问题以显示示例数据(源数据和查询结果),说明您希望发生什么以及当前查询出了什么问题。跨度>
  • where 子句中的 1 = 0 是什么意思?
  • @Farshad 以便开发人员可以在之后和/或轻松添加条件,而不是花时间寻找在哪里添加 where 语句。只是为了方便。

标签: sql sql-server operators where-clause


【解决方案1】:
select * from finalres where 
(status='rwd' and account# is null) 
 or  status not in ('xxx','ina','nfc')

您可以在以下链接查看此查询:

http://sqlfiddle.com/#!18/11b3d/2

 CREATE TABLE finalres
(
  [account] int,
  [ItemNo] varchar(32),
  status varchar(100)

) 

INSERT INTO finalres (account, ItemNo, status) VALUES
  ('1', '453', 'xxx'),
  ('2', '657', '34'),
  (null, '657', 'rwd')
  ;


account     ItemNo  status
2            657     34
(null)       657     rwd

【讨论】:

  • 它仍然不工作。它只适用于第一个条件
  • @unnikrishnan 你能把你表的一些数据放上来吗
【解决方案2】:

您有不想记录的状态列表(xxx、ina、nfc)。此外,当 account# 为空时,您只需要状态为 RWD 的记录,这意味着您需要将该状态添加到您不想要的状态列表中。这会给你一个这样的查询:

select
    *
from
    finalres
where
     status not in ('rwd','xxx','ina','nfc')
  or (status='rwd' and account is null)

【讨论】:

    【解决方案3】:

    问题是status not in ('xxx','ina','nfc') 允许结果包含任何status='rwd',即使account# 不为空。这使得(status='rwd' and account# is null) 变得多余。您需要在 status not in 查询中包含“rwd”。

    select 
    *
    from finalres
    where 1 = 0
    or (status='rwd' and account# is null)
    or status not in ('rwd','xxx','ina','nfc')
    

    【讨论】:

      【解决方案4】:

      试试这个,

          select * 
            from finalres 
           where (status='rwd' and account# is null) 
              or status not in ('xxx','ina','nfc')
      

      【讨论】:

      • 如果status = 'rwd' 那么status not in ('xxx','ina','nfc') 是多余的。这就像在说x=4 AND x NOT IN (1,2,3,5,6,7),你已经知道 x 是 4,所以它不能是任何其他值。
      • (X AND Y) AND Z 在功能上与X AND Y AND Z 相同 在功能上与X AND (Y AND Z) 在功能上与(X AND Z) AND Y 相同等等等等等等。
      猜你喜欢
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      相关资源
      最近更新 更多