1

我有这个查询。当我执行时,我得到了 Query 语句,但我想要这个查询的结果集。

我的查询是:

SELECT CONCAT('select * from ', table_name, ' union all ') AS CUSTOMQUERY
FROM   information_schema.tables
WHERE  table_name LIKE '%custom%'

我得到这个结果

select * from custom_70006 union all  
select * from custom_704306 union all  
select * from custom_700436 union all  
select * from custom_7000643 union all  
select * from custom_7000634 union all  
select * from custom_700046 union all  
select * from custom_700063 union all  
select * from custom_700062 union all 

但我想要这个特定列的结果集和相应的数据,最后union all应该删除。

请帮助我进行相关查询。

4

1 回答 1

1

我认为这就是你要找的:

SET GLOBAL group_concat_max_len = 4294967295;

SELECT @query1 := GROUP_CONCAT(CONCAT('SELECT * FROM ', table_name) SEPARATOR
                         ' UNION ALL ') AS CUSTOMQUERY
FROM   INFORMATION_SCHEMA.tables
WHERE  TABLE_SCHEMA = SCHEMA()
       AND table_name LIKE '%custom%';


PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;

示例:SQLFiddle

或将您的查询修改为:

SELECT @query1 := CONCAT('select * from ', table_name, ' union all ') AS
       CUSTOMQUERY
FROM   information_schema.tables
WHERE  table_name LIKE '%custom%'

从查询中删除最后一个'union all'字符串:

SET @query1 = TRIM(TRAILING 'union all' FROM TRIM(@query1));

PS: group_concat_max_len的默认值只有 1024。所以你需要将它设置为更高的值,否则你的查询的输出将被剥离,你可能会得到语法错误。

于 2012-08-30T05:44:39.670 回答