I have a problem when using AND and OR in SQL.
This returns a single record:
SELECT DISTINCT s.SupplierName, r.ReturnID, r.Reason
FROM tblSupplierProducts sp, tblReturns r,tblSuppliers s
WHERE sp.SupplierID=s.SupplierID
AND sp.ProductID=r.productID
AND r.Reason LIKE 'Unreadable disk'
This also returns a single record:
SELECT DISTINCT s.SupplierName, r.ReturnID, r.Reason
FROM tblSupplierProducts sp, tblReturns r,tblSuppliers s
WHERE sp.SupplierID=s.SupplierID
AND sp.ProductID=r.productID
AND r.Reason LIKE 'Scratched CD'
But when I do this:
SELECT DISTINCT s.SupplierName, r.ReturnID, r.Reason
FROM tblSupplierProducts sp, tblReturns r,tblSuppliers s
WHERE sp.SupplierID=s.SupplierID
AND sp.ProductID=r.productID
AND r.Reason LIKE 'Unreadable disk'
OR r.Reason LIKE 'Scratched CD'
The ‘Unreadable disk’ results are present and correct
but the ‘Scratched CD’ is not ( it has the same value for every different supplier)
If i swap them like this:
SELECT DISTINCT s.SupplierName, r.ReturnID, r.Reason
FROM tblSupplierProducts sp, tblReturns r,tblSuppliers s
WHERE sp.SupplierID=s.SupplierID
AND sp.ProductID=r.productID
AND r.Reason LIKE 'Scratched CD'
OR r.Reason LIKE 'Unreadable disk'
my first result is correct (‘Scratched CD’) while ‘Unreadable disk’ returns trhe same value for multiple suppliers.
It seems the AND OR is messing up the query why?
AND takes precedence over OR, so when you do your OR statement, that is the only criterion being met. Therefore, whichever statement is second in your query will have looser criteria. You need to explcitly group your query, like: