Mysql count()获取错误的结果

时间:2013-07-31 06:31:36

标签: mysql

我想找到当周的记录数。 我目前的疑问是:

SELECT Week(Str_to_date(products_options_values, '%m-%d-%Y'), 1) AS order_week,
       Year(Str_to_date(products_options_values, '%m-%d-%Y')) AS order_year,
       order_active,
       Count(op.sub_order_id) AS deliveries
FROM   orders_products_attributes opa
       LEFT JOIN orders_products op
              ON ( opa.orders_products_id = op.orders_products_id )
GROUP  BY order_week,
          order_year
HAVING order_week = '31'
       AND order_year >= '2013'
       AND order_active = 0
ORDER  BY order_week

它获取deliveries AS 2,其中实际上有4条记录,如果我在删除COUNTGROUP BY后运行相同的查询,则会正确显示所有4条记录行。其他周也会出现同样的问题,例如第34周有3条记录,但上面的查询却将其取为4。此外,另一个奇怪的事情是,在GROUP BY子句中,如果我删除order_weekorder_year中的任何一个,查询将返回一个空结果集。

知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

尝试将所有HAVING条件移至WHERE。另外Count(id) - 计算ID的UNIQUE值并非全部。如果您需要所有记录计数,请使用COUNT(*)

SELECT Week(Str_to_date(products_options_values, '%m-%d-%Y'), 1) AS order_week,
       Year(Str_to_date(products_options_values, '%m-%d-%Y')) AS order_year,
       order_active,
       Count(op.sub_order_id) AS deliveries
FROM   orders_products_attributes opa
       LEFT JOIN orders_products op
              ON ( opa.orders_products_id = op.orders_products_id )
WHERE order_week = '31'
       AND order_year >= '2013'
       AND order_active = 0

GROUP  BY order_week,
          order_year
ORDER  BY order_week