2015-12-30 69 views
2

表結構執行一個:生成多個查詢字符串,並通過一個

CREATE TABLE IF NOT EXISTS mysql.`my_autoinc` (
    `table_schema` VARCHAR(64) NOT NULL, 
    `table_name` VARCHAR(64) NOT NULL, 
    `auto_increment` INT(11) UNSIGNED NULL DEFAULT NULL, PRIMARY KEY (`table_schema`, `table_name`) 
) ENGINE=InnoDB; 

問題1:在任何DB命名table1table2所有表的 名單。

REPLACE INTO mysql.`my_autoinc` 
SELECT table_schema, table_name, NULL AS `auto_increment` 
FROM information_schema.tables 
WHERE table_name IN ("table1", "table2"); 

查詢1可以生成

table_schema | table_name | auto_increment 
=============================================== 
client_1  | table1  | NULL 
client_1  | table2  | NULL 
client_2  | table1  | NULL 
client_3  | table1  | NULL 

問題2:查詢字符串的 列表。

SELECT CONCAT(
    'REPLACE INTO my_autoinc ', 
    'SELECT "',table_schema,'", "',table_name,'", MAX(Id) FROM ', 
    '(' 
     'SELECT MAX(Id) AS Id FROM ', table_schema, '.', table_name, 
     ' UNION ', 
     'SELECT MAX(Id) AS Id FROM ', table_schema, '_history.', table_name, '_history', 
    ') t' 
) AS 'queries' 
FROM my_autoinc; 

當被執行由查詢2生成的查詢的列表。

table_schema | table_name | auto_increment 
=============================================== 
client_1  | table1  | 99 
client_1  | table2  | 60 
client_2  | table1  | 299 
client_3  | table1  | 399 

我已經嘗試過:GROUP_CONCAT但字符串的級聯長度超過1000所以,不能執行該長度的查詢。

更新:我不能做multiple statements in a prepare

需要解決方案:要執行查詢生成的查詢2 查詢2一個接一個。

回答

0

你可以從GROUP_CONCAT

-- for the session 
SET SESSION group_concat_max_len = 1000000; 

-- or global 
SET GLOBAL group_concat_max_len = 1000000; 
+0

但是,我不能準備多個語句。 http://stackoverflow.com/a/11635064/1753174 – bkmagnetron

0

設置最大lenght你可以用這樣一個存儲過程做到這一點,然後調用它:

DELIMITER $$ 
CREATE PROCEDURE doAllThings() 
BEGIN 
    DECLARE cursor_VAL VARCHAR(2000); 
    DECLARE done INT DEFAULT FALSE; 

    DECLARE cursor_i CURSOR FOR 
    SELECT CONCAT('REPLACE INTO mysql.my_autoinc ','SELECT "',table_schema,'", "',TABLE_NAME,'", MAX(Id) FROM ', '(SELECT MAX(Id) AS Id FROM ', table_schema, '.',TABLE_NAME,' UNION ','SELECT MAX(Id) AS Id FROM ', table_schema, '_history.', TABLE_NAME, '_history',') t') AS 'queries' FROM mysql.my_autoinc; 

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 

    OPEN cursor_i; 
    read_loop: LOOP 
    FETCH cursor_i INTO cursor_VAL; 
    IF done THEN 
     LEAVE read_loop; 
    END IF; 

    SET @SQL := queries; 
    PREPARE stmt FROM @SQL; 
    EXECUTE stmt; 
    DEALLOCATE PREPARE stmt;  

    END LOOP; 
    CLOSE cursor_i; 
END$$ 
DELIMITER ; 


-- call it 
call doAllThings(); 
相關問題