MySQL多个where条件,结果不满足所有条件

MySQL Multiple Where Conditions, Results Do Not Meet All Conditions

我有一个从 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');

结果: 如果 ordereddateduedate 超出日期范围,该项目将被排除在结果之外。

更改为 AND 而不是 OR


尝试过:

SELECT * FROM table
  WHERE status = 'Invoiced'
  AND (ordereddate AND duedate between '2009-12-01' AND '2011-12-30');

结果: Returns 一切正确,除非 ordereddateduedate 超出日期范围,该行将被排除在结果之外。

组合 ordereddateduedate where condition


尝试过:

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

这个似乎拉取了正确的状态,但是日期不正确,它似乎拉取了状态为已开票的任何东西,并忽略了日期范围。

如果我正确理解你的问题,你需要使用额外的括号:

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')
    )
;