mysql根据区域分区_mysql按某个字段,范围分区的代码

这篇博客详细介绍了如何使用MySQL的RANGE分区功能,根据日期字段(如'ymd')进行分区。示例代码展示了如何创建按年月分区的表,动态计算每个分区的结束时间,并在SQL语句中进行展示。
摘要由CSDN通过智能技术生成

public function partion($format = 'ymd')

{

$this->_initPts = 36;

$table = 'level';

$field = 'ymd';

$begin = '2016-12-31';

if($format == 'ymd')

{

//$this->_initPts = 41;

$sql = "ALTER TABLE `$table` PARTITION BY RANGE ($field) PARTITIONS " . ($this->_initPts+1) . ' ( ';

for($i = 0; $i <= $this->_initPts; ++$i)

{

// 起点

$next_str = $i ? strtotime('next month', $next_str) : strtotime(date($begin));

// 年

$y = date('y', $next_str);

// 月

$_m = date('m', $next_str);

if($_m - $m != 1 && $_m - $m != -11) // 在29号至31号时容易出错,会跳月

{

$next_str -= 24*3600*7; //减去7天,应该就可以退回上一个月了

// 年

$y = date('y', $next_str);

// 月

$m = date('m', $next_str);

}

else

{

$m = $_m;

}

// 下月的第一秒(也就是下个月1号的0:0:0)

$time = strtotime('next month', $next_str);

// "PARTITION p1703 VALUES LESS THAN (UNIX_TIMESTAMP('17-04-01 00:00:00')) COMMENT = '17年3月份充值表'

$sql .= "\n PARTITION p$y$m VALUES LESS THAN (" . date('ym01', $time) . ") COMMENT = '{$y}年{$m}月份',";

}

$sql = rtrim($sql, ',') . ');';

halt($sql);

}

$sql = "ALTER TABLE `$table` PARTITION BY RANGE ($field) PARTITIONS " . ($this->_initPts+1) . ' ( ';

for($i = 0; $i <= $this->_initPts; ++$i)

{

// 起点

$next_str = $i ? strtotime('next month', $next_str) : strtotime(date($begin));

// 年

$y = date('y', $next_str);

// 月

$_m = date('m', $next_str);

if($_m - $m != 1 && $_m - $m != -11) // 在29号至31号时容易出错,会跳月

{

$next_str -= 24*3600*7; //减去7天,应该就可以退回上一个月了

// 年

$y = date('y', $next_str);

// 月

$m = date('m', $next_str);

}

else

{

$m = $_m;

}

// 下月的第一秒(也就是下个月1号的0:0:0)

$time = strtotime('next month', $next_str);

// "PARTITION p1703 VALUES LESS THAN (UNIX_TIMESTAMP('17-04-01 00:00:00')) COMMENT = '17年3月份充值表'

$sql .= "\n PARTITION p$y$m VALUES LESS THAN (" . strtotime(date('y', $time) . '-' . date('m', $time) . '-01 0:0:0') . ") COMMENT = '{$y}年{$m}月份',";

}

$sql = rtrim($sql, ',') . ');';

halt($sql);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值