Mysql从多个表中进行选择,每个月都会创建一个新表


Mysql select from multiple tables and a new table is created every month

我现在有三个表:cdr、cdr_201502和cdr_201503,下个月系统将创建一个新的cdr_201504等等。我正在做一个php页面,从数据库中选择一些信息,我需要从所有表中进行选择,我需要自动化这件事,我可以使用联合选择或内部联接,但每个月我都需要为新创建的表编写一个新的联合选择。。。表具有相同的列。请帮助我已经谷歌了所有的页面,但找不到任何与我的需求相关的页面。

我不能把所有的代码都放在这里,但我可以举一个例子:

select * from cdr where src='470' and calltype like '%' 
and billable>'-1'  and datetime>'2015-01-01 00:00:00' and datetime 
<'2015-  03-30     23:59:59' order by datetime desc
union all
select * from cdr_201502 where src='470' and calltype like '%' 
and billable>'-1'  and datetime>'2015-01-01 00:00:00' and datetime 
<'2015-  03-30     23:59:59' order by datetime desc
union all 
select * from cdr_201503 where src='470' and calltype like '%' 
and billable>'-1'  and datetime>'2015-01-01 00:00:00' and datetime 
<'2015-  03-30     23:59:59' order by datetime desc;

下个月我将需要添加一个新的工会,那么如何实现自动化呢?

问题:我可以使用查询从information_schema中选择表吗然后使用select,或者创建一个触发器来更新表(但我需要每月更改触发器)?

第1部分:我可以使用查询从information_schema中选择表,然后使用select

我们可以使用query从information_schema 中获取表名

 SELECT table_name FROM information_schema.tables
 WHERE table_type = 'BASE TABLE'
 AND table_schema = 'database-name'
 AND table_name like 'cdr%';

如果我们在表名创建中遵循一种模式,我们也可以创建一个小动态的查询,我们可以根据日期时间戳在$cdr这样的变量中获取表名,并在查询中使用它,在循环中增加$cdr的值

select * from '".$cdr." ' where src='470' and calltype like '%'

第2部分:从具有相同结构的多个表中选择列

使用UNION

(select * from cdr where src='470' and calltype like '%' )
UNION 
(select * from cdr_201502 where src='470' and calltype like '%' );

使用ALIAS

SELECT cdr.id, cdr.name, cdr_201502.id 
FROM cdr
  INNER JOIN cdr_201502 on cdr.id = cdr_201502.id