1、建表
该表根据create_time列的年份进行分区,每个分区对应一个年份。例如,p0分区存储2020年之前的数据,p1分区存储2021年的数据,以此类推。
CREATE TABLE my_table (
id INT PRIMARY KEY,
name VARCHAR(50),
create_time DATE
)
PARTITION BY RANGE (YEAR(create_time))
(
PARTITION p0 VALUES LESS THAN (2020),
PARTITION p1 VALUES LESS THAN (2021),
PARTITION p2 VALUES LESS THAN (2022),
PARTITION p3 VALUES LESS THAN (2023)
);
2、java代码处理
mapper
@Mapper
public interface MyTableMapper extends BaseMapper<MyTable> {
List<MyTable> selectByTime(@Param("startTime") Date startTime, @Param("endTime") Date endTime, @Param("partitionName") String partitionName);
}
xml
<select id="selectByTime" resultMap="BaseResultMap">
SELECT *
FROM my_table PARTITION (${partitionName})
WHERE create_time BETWEEN #{startTime} AND #{endTime}
</select>
service
@Service
public class MyService {
@Autowired
private MyTableMapper myTableMapper;
public List<MyTable> queryByTimeRange(Date startTime, Date endTime) {
List<MyTable> result = new ArrayList<>();
String[] partitionNames = getPartitionNames(startTime, endTime);
for (String partitionName : partitionNames) {
List<MyTable> list = myTableMapper.selectByTime(startTime, endTime, partitionName);
result.addAll(list);
}
return result;
}
private String[] getPartitionNames(Date startTime, Date endTime) {
int startYear = DateUtil.year(startTime);
int endYear = DateUtil.year(endTime);
List<String> partitionNames = new ArrayList<>();
for (int year = startYear; year <= endYear; year++) {
partitionNames.add("p" + year);
}
return partitionNames.toArray(new String[0]);
}
}