SQL选择多个AND和OR

时间:2012-08-23 08:55:39

标签: sql-server-2008 select where

我坐在逻辑问题上,我只是越来越困惑自己。

示例表

ID | CustID |任务|确认|取消|完成

1 | 20 |文字| 1 | 0 | 0
2 | 20 |文字| 1 | 1 | 0
3 | 20 |文字| 1 | 0 | 1
4 | 17 |文字| 0 | 1 | 0
5 | 17 |文字| 1 | 0 | 0
6 | 20 |文字| 1 | NULL | NULL
7 | 20 |文字| 0 | 1 | NULL

我希望选择custID = 20的所有任务并确认= 1。如果任务被取消= 1或已完成= 1,则不要返回记录。

在这种情况下,返回的行将是1和6。

到目前为止,我的查询是

SELECT *
FROM table1
WHERE    
 (CustID = 20 AND Confirmed = 1 AND Cancelled <> 1 AND Completed <> 1) OR
 (CustID = 20 AND Confirmed = 1 AND Cancelled = 1 AND Completed <> 1) OR
 (CustID = 20 AND Confirmed = 1 AND Cancelled <> 1 AND Completed = 1)

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:13)

您可以将其简化为:

SELECT * FROM table1
WHERE CustID = 20
  AND Confirmed = 1
  AND (Cancelled <> 1 OR Cancelled IS NULL)
  AND (Completed <> 1 OR Completed IS NULL)

在将实际值与NULL进行比较时,您必须小心(并且非常明确),因为均等和不等式都会排除它们。

答案 1 :(得分:2)

SELECT *
FROM table1
WHERE    
    CustID = 20 AND Confirmed = 1 AND NOT (Cancelled = 1 OR Completed = 1)  

答案 2 :(得分:-1)

SELECT * FROM thk_basvuru WHERE thk_status in (8,23,33) or thk_olo_status not in (4,6,9,11,12)