优化MySQL查询以使用时间范围获取数据

时间:2010-01-16 11:47:43

标签: mysql

我正在使用Google Chart API为产品销售报告构建折线图,并且每天使用UNION ALL作为粘合剂,基本上在每天的循环中运行相同的查询来分隔数据。

E.g。一年的报告将使用UNION ALL 365次重复查询。

我猜这不是一个最好的做法 - 例如,如果有人如此善良并指出我如何优化这个查询的正确方向,我将非常感激。

  SELECT SUM(op.qty) AS qty
  FROM uc_order_products op
  LEFT JOIN uc_orders o ON o.order_id = op.order_id
  LEFT JOIN node n ON n.nid = op.nid
  LEFT JOIN node_type nt ON nt.type = n.type
  WHERE (o.created > 1247695200) AND (o.created < 1247781600)
  AND (o.order_status = 'completed')
  AND (nt.type = 'book' OR nt.type = 'digital_movie')

  UNION ALL 

  SELECT SUM(op.qty) AS qty
  FROM uc_order_products op
  LEFT JOIN uc_orders o ON o.order_id = op.order_id
  LEFT JOIN node n ON n.nid = op.nid
  LEFT JOIN node_type nt ON nt.type = n.type
  WHERE (o.created > 1247781600) AND (o.created < 1247868000)
  AND (o.order_status = 'completed')
  AND (nt.type = 'book' OR nt.type = 'digital_movie')

  UNION ALL

  SELECT SUM(.......

感谢所有快速回复!使用jspcal中的查询示例,我的查询结果如下:

  SELECT SUM(op.qty) AS qty, DATE_FORMAT(FROM_UNIXTIME(o.created),'%d-%m-%Y') AS day
  FROM uc_order_products op
  LEFT JOIN uc_orders o ON o.order_id = op.order_id
  LEFT JOIN node n ON n.nid = op.nid
  LEFT JOIN node_type nt ON nt.type = n.type
  WHERE (o.created > 1247695200) AND (o.created < 1263596400)
  AND (o.order_status = 'completed')
  AND (nt.type = 'book' OR nt.type = 'digital_movie')
  GROUP BY day

使用PHP,我将完整的日期范围数组(与查询结果中的strtotime($data->day)匹配的数组键)组合在一起,以获得没有销售的日子。

2 个答案:

答案 0 :(得分:1)

你可以按天分组:

select sum(op.qty) as qty, date_format(o.created, '%Y-%m-%d') as day
from ... where ... o.created >= subdate(now(), interval 1 year) and
o.created <= now() group by day order by day

将报告数据集中一年中每一天的总和

答案 1 :(得分:0)

你应该能够转换

WHERE (o.created > 1247695200) AND (o.created < 1247781600)
AND (o.order_status = 'completed')
AND (nt.type = 'book' OR nt.type = 'digital_movie')


WHERE (o.created > 1247781600) AND (o.created < 1247868000)     
AND (o.order_status = 'completed')     
AND (nt.type = 'book' OR nt.type = 'digital_movie')

....

类似

WHERE   (
                (o.created > 1247695200) AND (o.created < 1247781600)
            OR  (o.created > 1247781600) AND (o.created < 1247868000)
            ...
        )
AND (o.order_status = 'completed')
AND (nt.type = 'book' OR nt.type = 'digital_movie')