MySQL数据库按时间分表的查询方法

11 篇文章 0 订阅

分表规则:按月分表,每个月一张表,表的字段和类型都相同。 如 test_table_202011
查询方法:

$start_date  = strtotime('2020-01-01 00:00:00'); //开始时间戳
$end_date    = strtotime('2020-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 * FROM test_table_{$month_begin}";

while(intval($month_next) <= intval($month_end)){
    $UNION_SQL .= " UNION ALL SELECT * FROM test_table_{$month_next}";
    $month_plus += 1;
    $month_next  = date('Ym', strtotime("+{$month_plus} months", $start_date));
}

$sql = "SELECT * FROM ($UNION_SQL) t WHERE 1 AND create_time BETWEEN $start_date AND $end_date";
$dt  = DB::query($sql);

可根据自己的需求封装成函数调用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值