Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select with multiple AND and OR's

I'm sitting with a logic issues and I'm just confusing myself more and more.

Example table

ID | CustID | Task | Confirmed | Cancelled | Completed

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

I wish to select all tasks for custID = 20 and are confirmed=1. If the task is cancelled=1 or completed=1, do not return the record.

In this case, returned rows would be 1 and 6.

My query thus far is

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)

Any help would be greatly appreciated.

like image 878
Deon Avatar asked Aug 23 '12 08:08

Deon


2 Answers

You can simplify that to:

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

You have to be careful (and very explicit) when comparing real values with NULLs, since equalities and inequalities both exclude them.

like image 150
paxdiablo Avatar answered Jan 04 '23 06:01

paxdiablo


SELECT *
FROM table1
WHERE    
    CustID = 20 AND Confirmed = 1 AND NOT (Cancelled = 1 OR Completed = 1)  
like image 27
TheHe Avatar answered Jan 04 '23 06:01

TheHe