我有一个从expressJS注入MySQL的查询,但是当执行这些查询时。有时我会返回不正确满足条件的数据。
原始
:SELECT * FROM table
WHERE status = 'Invoiced'
AND (ordereddate between '2009-12-01' AND '2011-12-30')
OR (duedate between '2009-12-01' AND '2011-12-30');
结果:
Ordered Date Due Date Status
2009-11-18 2009-12-16 Invoiced
2009-11-18 2009-12-14 Cancelled
结果显示具有任何状态的项目均被拉出,但满足日期条件。
尝试过:
SELECT * FROM table
WHERE (status = 'Invoiced')
AND (ordereddate between '2009-12-01' AND '2011-12-30')
AND (duedate between '2009-12-01' AND '2011-12-30');
结果:
如果ordereddate
或duedate
不在日期范围内,则该项目将不在结果之列。
更改为AND
,而不是OR
尝试过:
SELECT * FROM table
WHERE status = 'Invoiced'
AND (ordereddate AND duedate between '2009-12-01' AND '2011-12-30');
结果:
正确返回所有内容,除非ordereddate
或duedate
超出日期范围,否则该行将不包含在结果中。
结合ordereddate
和duedate
的条件
尝试过:
SELECT * FROM table
WHERE status = 'Invoiced'
AND (ordereddate OR duedate between '2009-12-01' AND '2011-12-30');
结果:
Ordered Date Due Date Status
2008-07-07 2008-07-28 Invoiced
2008-07-07 2008-07-25 Invoiced
2008-07-07 2008-07-23 Invoiced
这似乎拉出了正确的状态,但是日期不正确,它似乎在拉出状态为“已开具发票”的任何东西,而忽略了日期范围。
答案 0 :(得分:0)
如果我正确理解了您的问题,则需要使用其他括号:
SELECT
*
FROM
table
WHERE
status = 'Invoiced'
AND (
(ordereddate between '2009-12-01' AND '2011-12-30')
OR (duedate between '2009-12-01' AND '2011-12-30')
)
;