MYSQL如何联合多个“未知”表

时间:2017-04-12 14:00:33

标签: mysql union prepare

我有一些结构为“TableNameYYMM”的历史表 如何UNION所有以“TableName”开头的历史表?

我需要搜索所有历史记录表。

我尝试使用PREPARE Execute和DEALLOCATE。 但每次都会出现SQL错误。

SET group_concat_max_len = 2048;

SET @startQuery = (SELECT CONCAT('SELECT col1, col2, col3 FROM ',TABLE_SCHEMA,'.', TABLE_NAME)
FROM information_schema.tables 
WHERE 
    ENGINE = 'MyISAM'
    AND TABLE_NAME like 'hist%'
ORDER BY TABLE_NAME
LIMIT 0,1);



SET @subquery = (SELECT GROUP_CONCAT(@startquery, 'UNION ALL SELECT col1, col2, col3 FROM ',TABLE_SCHEMA,'.', TABLE_NAME)
FROM information_schema.tables 
WHERE 
    ENGINE = 'MyISAM'
    AND TABLE_NAME like 'hist%'
ORDER BY TABLE_NAME
LIMIT 1,1000);


PREPARE stmt1 FROM '? AS combinedTable';
EXECUTE stmt1 USING @subquery;
DEALLOCATE PREPARE stmt1;

在第1部分(@startquery)上,我尝试获取Query的第一部分 “从table1中选择xxx”

在第2部分(@subquery)我试图获得所有联盟(来自table2-max 1000)

select xxx from table1
UNION ALL select xxx from table2
UNION ALL select xxx from table3
...

我希望有人对这个问题有所了解。

1 个答案:

答案 0 :(得分:0)

/*
create table history1701 (id int,col1 int,col2 int);
create table history1702 (id int,col1 int,col2 int);
create table history1703 (id int,col1 int,col2 int);
create table history1704 (id int,col1 int,col2 int);
insert into history1701 values (1,1,1);
insert into history1702 values (2,2,2);
insert into history1703 values (3,3,3);
insert into history1704 values (4,4,4);
*/

SET @startQuery = (SELECT CONCAT('SELECT col1, col2 FROM ',TABLE_SCHEMA,'.', TABLE_NAME)
FROM information_schema.tables 
WHERE 
#    ENGINE = 'MyISAM'    AND 
    TABLE_NAME like 'hist%17%'
ORDER BY TABLE_NAME
LIMIT 0,1);

SET @subquery = (
SELECT group_CONCAT(' UNION ALL SELECT col1, col2 FROM ',TABLE_SCHEMA,'.', TABLE_NAME order by table_name separator ' ' )
FROM information_schema.tables 
WHERE 
     TABLE_NAME like 'hist%17%'
     and table_name <> (
     select table_name from information_schema.tables WHERE 
#    ENGINE = 'MyISAM'    AND 
    TABLE_NAME like 'hist%17%'
    ORDER BY TABLE_NAME
    LIMIT 0,1
    )
);


select @startquery;
set @subquery = concat(@startquery,@subquery);

PREPARE stmt1 FROM @subquery;
EXECUTE stmt1 ;

DEALLOCATE PREPARE stmt1;

在你的代码中第一个集合@subquery中的限制1,1000返回一个空值(不好),并在每个union之后生成一个逗号(也不好)。我修改了这个以排除第一个历史表并将组concat分隔符更改为空格并将order by移动到group_concat中。