当前位置: 代码网 > it编程>数据库>Mysql > Mysql表如何按照日期字段的年月分区

Mysql表如何按照日期字段的年月分区

2025年04月12日 Mysql 我要评论
一、创键表时直接设置分区create table your_table_name ( id int not null auto_increment, sale_date date not

一、创键表时直接设置分区

create table your_table_name (
    id int not null auto_increment,
    sale_date date not null,
    amount decimal(10, 2) not null,
    primary key (id, sale_date)
) partition by range columns(sale_date) (
    partition p2020_01 values less than ('2020-02-01'),
    partition p2020_02 values less than ('2020-03-01'),
    partition p2020_03 values less than ('2020-04-01'),
    partition p2021_01 values less than ('2021-02-01'),
    partition p_max values less than (maxvalue)
);

二、已有表分区

1、分区的前置条件

确保主键或唯一键包含分区键,若已经创建表可以修改

alter table your_table_name drop primary key;

alter table your_table_name 
add primary key (id, xxdate);

2、分区操作

查询需要分区的日期字段所含有的年月

select distinct date_format(xxdate, '%y-%m') as ym
from your_table_name 
order by ym;

根据上面sql语句查询的年月数据创建分区

# 我这只有202307、202308两个月数据
alter table your_table_name 
partition by range columns(xxdate) (
    partition p2023_07 values less than ('2023-08-01'),
    partition p2023_08 values less than ('2023-09-01'),
    partition p_max values less than (maxvalue)
);

三、验证

explain  select * from your_table_name where xxdate between '2023-07-01' and '2023-07-31';

partitions 命中一个目标分区则分区成功,如:partitions列的值为 p2023_07

四、注意

如果有新的月份分区需要增加,则需要手动去修改,否则归为p_max分区影响查询效率

alter table your_table_name 
partition by range columns(xxdate) (
    partition p2023_07 values less than ('2023-08-01'),
    partition p2023_08 values less than ('2023-09-01'),
    # 在这里添加
    partition p_max values less than (maxvalue)
);

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com