SQL查询给出了错误的结果

时间:2011-05-13 16:45:54

标签: mysql sql

当我运行以下查询时,它只显示1行。基于“created_date”条件,就像我删除“created_date”条件并保持“status_change_date”条件一样,它显示3行。

我想查看在指定时间内创建或修改的所有项目。我无法在查询

中找到错误的内容
`SELECT DISTINCT products.id AS product, status.id AS stat, COUNT(*) AS total FROM items 
      INNER JOIN products ON (items.fk_product_id = products.id) 
      INNER JOIN status ON (items.fk_status = status.id) 
      WHERE DATE(items.status_change_date) BETWEEN '2011-04-13' AND '2011-05-13' 
      OR DATE(items.created_date) BETWEEN '2011-04-13' AND '2011-05-13' 
      AND status.id = 2 
      GROUP BY products.name, status.name order by products.name`

3 个答案:

答案 0 :(得分:2)

我感觉条件正在像这样进行评估

status_change_date or (created_date and status.id = 2)

您可以尝试使用括号来指定条件的分组

( DATE(items.status_change_date)... OR DATE(items.created_date)... )
    AND status.id = 2

答案 1 :(得分:1)

在日期条款周围加上括号:

  WHERE (DATE(items.status_change_date) BETWEEN '2011-04-13' AND '2011-05-13' 
  OR DATE(items.created_date) BETWEEN '2011-04-13' AND '2011-05-13')
  AND status.id = 2 

答案 2 :(得分:1)

您的WHERE子句看起来不对,请尝试:

WHERE 
    (DATE(items.status_change_date) BETWEEN '2011-04-13' AND '2011-05-13' 
    OR DATE(items.created_date) BETWEEN '2011-04-13' AND '2011-05-13')
        AND status.id = 2 
        GROUP BY products.name, status.name order by products.name