mysql 按月分表的查询_mysql按月分表, 组合查询

每个月月底最后一天建好下个月的空表 或每年底建1到12月的空表 , table_201901,table_201902,table_201903

增加记录不需要修改,insert到当月对应表就好了。

查询的时候需要代码中判断查询时间范围,union范围内的月份表,组合出查询SQL,  比如查询5月5日到6月5日的数据 ,跨5月和6月表

组合子查询  (select * from table_201905 UNION ALL select * from table_201906 )

再从子查询结果查询条件下的记录,  不要忘记子查询起个别名    select * from (select * from table_201905 UNION ALL select * from table_201906 ) tmp where dateline between 5月5日 and 6月5日

看代码

//注册到月份表

$sql = "INSERT INTO tbl_view_".date('Ym')."(ip,city,dateline) VALUES('127.0.0.1','CHINA',1562065253)";

$id = DB::query($sql);

//查询的时候按时间条件组合查询SQL

$start_date = strtotime('2019-01-01 00:00:00');

$end_date = strtotime('2019-07-01 23:59:59');

$month_begin = date('Ym', $start_date);

$month_end = date('Ym', $end_date);

$month_plus = 1;

$month_next = date('Ym', strtotime("+{$month_plus} months", $start_date));

$UNION_SQL = "SELECT ip,city,dateline FROM tbl_view_{$month_begin}";

while(intval($month_next) <= intval($month_end)){

$UNION_SQL .= " UNION ALL SELECT ip,city,dateline FROM tbl_view_{$month_next}";

$month_plus += 1;

$month_next = date('Ym', strtotime("+{$month_plus} months", $start_date));

}

$sql = "SELECT * FROM ($UNION_SQL) t WHERE 1 AND dateline BETWEEN $start_date AND $end_date";

$dt = DB::query($sql);

?>

来源:https://www.cnblogs.com/6min/p/11122919.html

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值