生成多个查询字符串并逐个执行

时间:2015-12-30 10:25:28

标签: mysql database auto-increment

表格结构:

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: 任何数据库中名为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 :(得分:0)

您可以设置GROUP_CONCAT

的最大长度
-- for the session
SET SESSION group_concat_max_len = 1000000;

-- or global
SET GLOBAL group_concat_max_len = 1000000;

答案 1 :(得分:0)

您可以使用这样的存储过程来执行此操作,然后调用它:

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();