SQL和OR评估不同的结果

时间:2012-10-18 18:46:25

标签: sql sql-server

在SQL中使用AND和OR时遇到问题。

这会返回一条记录:

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' 

这也会返回一条记录:

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'

但是当我这样做时:

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'

“不可读磁盘”结果存在且正确 但'Scratched CD'不是(它对每个不同的供应商都有相同的价值) 如果我像这样交换它们:

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'

我的第一个结果是正确的('Scratched CD'),而'Unreadable disk'为多个供应商返回相同的值。

似乎AND OR弄乱了查询原因?

4 个答案:

答案 0 :(得分:2)

LIKE旨在与%通配符一起使用来表示0+随机字符。

在组合AND和OR时使用(),以防止含糊不清的where子句

答案 1 :(得分:2)

您的操作顺序有问题。你绝对应该使用paranthesis来确保逻辑已知。隐含的是这个:

    USE CNB_ONLINE
    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')

你应该有这样的代码:

    USE CNB_ONLINE
    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')

您可以在此处找到优先顺序:http://msdn.microsoft.com/en-us/library/ms190276.aspx并且您会注意到在OR之前对AND进行评估。

答案 2 :(得分:1)

AND优先于OR,因此当您执行OR语句时,这是唯一符合的标准。因此,在查询中以第二个为准的语句将具有更宽松的标准。您需要对查询进行explcitly分组,例如:

WHERE sp.SupplierID=s.SupplierID
AND sp.ProductID=r.productID
AND (r.Reason LIKE  'Scratched CD'
OR r.Reason LIKE 'Unreadable disk')

答案 3 :(得分:1)

当你使用LIKE时,你真的应该输入一些像%这样的通配符。否则,如果您要查找文字字符串,只需使用=

尝试围绕WHERE子句的各个部分包装括号,以查看是否有帮助:

AND sp.ProductID=r.productID
AND ((r.Reason = 'Scratched CD')
    OR (r.Reason = 'Unreadable disk'))