我有以下查询:
SELECT * FROM project WHERE year = 11 AND orderDate LIKE ? OR orderNo LIKE ? OR prodNo LIKE ? OR prodName LIKE ? OR inquiryDate LIKE ? OR confirmDate LIKE ? OR deliveryLT LIKE ? OR deliveryRiis LIKE ? OR signsPrice LIKE ? OR vrPrice LIKE ? OR deliveryPrice LIKE ? OR unexpectPrice LIKE ? OR riisBonus LIKE ? OR kennBonus LIKE ? OR profit LIKE ? OR profitPercent LIKE ? OR quantity LIKE ?;
问题是,即使列年份不是11,我仍然收到数据,是因为我使用OR? (使用问号是因为我使用的是preparedStatements)。
当我这样做时
SELECT * FROM project WHERE year = 11 AND orderDate LIKE ? ;
它工作正常,所以我认为它是正确的吗?如果是这样,我该如何解决?我希望其中一个是真实的,一年是100%真实的;
答案 0 :(得分:1)
SQL rules of precedence状态“和”出现在“或”之前,因此您的SQL等同于:
SELECT * FROM project WHERE ( year = 11 AND orderDate LIKE ? ) OR orderNo LIKE ?
OR prodNo LIKE ? OR prodName LIKE ? OR inquiryDate LIKE ?
使用添加的括号覆盖它以满足您的要求:
SELECT * FROM project WHERE year = 11 AND
(orderDate LIKE ? OR orderNo LIKE ?
OR prodNo LIKE ? OR prodName LIKE ? OR inquiryDate LIKE ?)
答案 1 :(得分:0)
是; AND在OR
之前处理,因此您实际上是在查询year = 11 and orderDate LIKE ?
或满足任何其他条件的所有项目。
您需要使用括号,以明确哪些条件适用于AND
,哪些条件应为OR
。
我认为你希望它看起来像这样:
SELECT * FROM project WHERE year = 11 AND (orderDate LIKE ? OR orderNo LIKE ? OR prodNo LIKE ? OR prodName LIKE ? OR inquiryDate LIKE ? OR confirmDate LIKE ? OR deliveryLT LIKE ? OR deliveryRiis LIKE ? OR signsPrice LIKE ? OR vrPrice LIKE ? OR deliveryPrice LIKE ? OR unexpectPrice LIKE ? OR riisBonus LIKE ? OR kennBonus LIKE ? OR profit LIKE ? OR profitPercent LIKE ? OR quantity LIKE ?)