批量遷移數據

用存儲過程,將總表中的數據按照必定規則遷移到新的分表中。mysql

USE tobresume;

DROP PROCEDURE IF EXISTS Dist_talent;

DELIMITER $$

CREATE PROCEDURE Dist_talent()

BEGIN

DECLARE db_name VARCHAR(20);
DECLARE table_name VARCHAR(20);
DECLARE table_pro CHAR(18);
DECLARE sql_text VARCHAR(3000);
DECLARE i INT;
DECLARE j VARCHAR(20);

SET db_name='tobresume';
SET table_name='';
SET table_pro = '_talent_dir_resume';
SET sql_text='';
SET i=0;
SET j='';

WHILE i<=128 DO
IF i<10 THEN
SET j=CONCAT('0',i);
ELSE
SET j=LPAD(LCASE(HEX(i)),2,'0');
END IF;

SET table_name=CONCAT(j,table_pro);
      
SET sql_text=CONCAT('INSERT INTO ', db_name, '.', table_name, '(uid,top_id,dir_id,parent_id,resume_id,is_deleted,created,updated) ', 'SELECT uid,top_id,dir_id,parent_id,resume_id,is_deleted,created,updated FROM talent_dir_resume WHERE lower(lpad(conv(floor(conv(left(md5(top_id),2),16,10)/2),10,16),2,\'0\'))=\'', j, '\';');

SELECT sql_text;
SET @sql_text=sql_text;
PREPARE stmt FROM @sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET i=i+1;
END WHILE;

END$$

DELIMITER ;

call Dist_talent();

結果:sql

+-----------------------------------------------------------------------------------------+
| sql_text                                                                                                                                                                                                                                                                                        |
+--------------------------------------------------------------------------------------------------+
| INSERT INTO tobresume.80_talent_dir_resume(uid,top_id,dir_id,parent_id,resume_id,is_deleted,created,updated) SELECT uid,top_id,dir_id,parent_id,resume_id,is_deleted,created,updated FROM talent_dir_resume WHERE lower(lpad(conv(floor(conv(left(md5(top_id),2),16,10)/2),10,16),2,'0'))='80'; |
+-----------------------------------------------------------------------------------------+
1 row in set (1.33 sec)

Query OK, 0 rows affected (1.34 sec)

mysql> select count(1) from 21_talent_dir_resume;
+----------+
| count(1) |
+----------+
|      966 |
+----------+
1 row in set (0.00 sec)

注意: 使用存儲過程要注意主從分離的狀況。bash

相關文章
相關標籤/搜索