MySQL之查询多个相同表结构的数据

项目中数据量比较大需要每个月分一次表,按照时间分表;

分表查询逻辑:先按条件查询出要查询的表,再去多张表里面查询符合条件的数据

MySQL查表语句:

// 这种方式不支持条件查询
show tables;

// 这种方式可以根据table_name字段匹配符合条件的表
select * from information_schema.tables where table_name like 'th%';

分出来的表一定是表结构相同的数据表,多张相同数据结构的表查询语句:

// union all 关键字查询
select * from thermal_oil_pipeline_202009060553 p
union all
select * from thermal_oil_pipeline_202009060553 p
union all
select * from thermal_oil_pipeline_202009060553 p

分页查询会用到符合条件数据总数量这个数据,分表查询符合条件数据总量sql如下:

select sum(count) from (
	select count(p.id) as count from thermal_oil_pipeline as p 
	where  equipmentNo='FIC4' and createTime >= '2020-09-02 14:30:44' and createTime <= '2020-09-06 14:30:44'
	union all select count(p.id) as count from thermal_oil_pipeline_202009060553 as p 
	where  equipmentNo='FIC4' and createTime >= '2020-09-02 14:30:44' and createTime <= '2020-09-06 14:30:44'
) as total;

  

原文地址:https://www.cnblogs.com/mxh-java/p/13621018.html