集群

联合索引

分库分表

统计时间

获取最近七天时间

  1. SELECT CURDATE() UNION ALL
  2. SELECT DATE_SUB( CURDATE(), INTERVAL 1 DAY ) UNION ALL
  3. SELECT DATE_SUB( CURDATE(), INTERVAL 2 DAY ) UNION ALL
  4. SELECT DATE_SUB( CURDATE(), INTERVAL 3 DAY ) UNION ALL
  5. SELECT DATE_SUB( CURDATE(), INTERVAL 4 DAY ) UNION ALL
  6. SELECT DATE_SUB( CURDATE(), INTERVAL 5 DAY ) UNION ALL
  7. SELECT DATE_SUB( CURDATE(), INTERVAL 6 DAY )

image.png

获取最近七天周

  1. SELECT DATE_FORMAT( CURDATE(), '%Y-%u' ) AS weeks UNION ALL
  2. SELECT DATE_FORMAT( DATE_SUB( CURDATE(), INTERVAL 1 WEEK ), '%Y-%u' ) AS weeks UNION ALL
  3. SELECT DATE_FORMAT( DATE_SUB( CURDATE(), INTERVAL 2 WEEK ), '%Y-%u' ) AS weeks UNION ALL
  4. SELECT DATE_FORMAT( DATE_SUB( CURDATE(), INTERVAL 3 WEEK ), '%Y-%u' ) AS weeks UNION ALL
  5. SELECT DATE_FORMAT( DATE_SUB( CURDATE(), INTERVAL 4 WEEK ), '%Y-%u' ) AS weeks UNION ALL
  6. SELECT DATE_FORMAT( DATE_SUB( CURDATE(), INTERVAL 5 WEEK ), '%Y-%u' ) AS weeks UNION ALL
  7. SELECT DATE_FORMAT( DATE_SUB( CURDATE(), INTERVAL 6 WEEK ), '%Y-%u' ) AS weeks

image.png

获取最近七月的时间

  1. SELECT DATE_FORMAT( CURDATE(), '%Y-%m' ) AS `year_month` UNION
  2. SELECT DATE_FORMAT(( CURDATE() - INTERVAL 1 MONTH ), '%Y-%m' ) AS `year_month` UNION
  3. SELECT DATE_FORMAT(( CURDATE() - INTERVAL 2 MONTH ), '%Y-%m' ) AS `year_month` UNION
  4. SELECT DATE_FORMAT(( CURDATE() - INTERVAL 3 MONTH ), '%Y-%m' ) AS `year_month` UNION
  5. SELECT DATE_FORMAT(( CURDATE() - INTERVAL 4 MONTH ), '%Y-%m' ) AS `year_month` UNION
  6. SELECT DATE_FORMAT(( CURDATE() - INTERVAL 5 MONTH ), '%Y-%m' ) AS `year_month` UNION
  7. SELECT DATE_FORMAT(( CURDATE() - INTERVAL 6 MONTH ), '%Y-%m' ) AS `year_month`

image.png

获取每天的数据量

获取到需要点时间日期后,可和数据表进行左连接,从而查询每个时间段的数据量
例如:查询new表最近7天,每天的数据总数

  1. SELECT
  2. a.tscreate,
  3. IFNULL( b.count, 0 ) as count
  4. FROM
  5. (
  6. SELECT CURDATE() AS tscreate UNION ALL
  7. SELECT DATE_SUB( CURDATE(), INTERVAL 1 DAY ) AS tscreate UNION ALL
  8. SELECT DATE_SUB( CURDATE(), INTERVAL 2 DAY ) AS tscreate UNION ALL
  9. SELECT DATE_SUB( CURDATE(), INTERVAL 3 DAY ) AS tscreate UNION ALL
  10. SELECT DATE_SUB( CURDATE(), INTERVAL 4 DAY ) AS tscreate UNION ALL
  11. SELECT DATE_SUB( CURDATE(), INTERVAL 5 DAY ) AS tscreate UNION ALL
  12. SELECT DATE_SUB( CURDATE(), INTERVAL 6 DAY ) AS tscreate
  13. ) a
  14. LEFT JOIN (
  15. SELECT
  16. count(*) AS count,
  17. DATE( tscreate ) AS tscreate
  18. FROM
  19. new
  20. GROUP BY
  21. DAY ( tscreate )) b ON a.tscreate = b.tscreate
  22. ORDER BY a.tscreate ASC

image.png