目前,我有3个表:cdr,cdr_201502和cdr_201503,下个月系统将创建一个新的cdr_201504,依此类推。我正在做一个php页面,以从数据库中选择一些信息,我需要从所有表中进行选择,并且我需要使这件事自动化,我可以使用联合选择或内部联接,但是每个月我都需要为新的联合写一个新的联合选择。创建的表格...表格具有相同的列。请帮助我已经有google'd所有页面,但找不到与我的需求有关的任何页面。
我不能将所有代码放在这里,但我可以举个例子:
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
我们可以使用查询从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
关于php - MySQL从多个表中选择,每月创建一个新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29348506/