Skip to content

Instantly share code, notes, and snippets.

@jgdoncel
Last active August 29, 2015 14:22
Show Gist options
  • Save jgdoncel/726312827e96e926b057 to your computer and use it in GitHub Desktop.
Save jgdoncel/726312827e96e926b057 to your computer and use it in GitHub Desktop.
Particionar tabla Ejemplo suponiendo una tabla test (id,fecha) que pretendemos particionar por meses. Conviene crear el campo para el HASH debido a que MySQL filtra las consultas por particiones siempre que se incluya el HASH en el filtro. https://dev.mysql.com/doc/refman/5.6/en/partitioning-pruning.html
-- Crear nuevo campo
ALTER TABLE `test` ADD COLUMN `ts_year_month` int(11);
-- Insertar valores en el campo para los registros actuales
UPDATE `test` SET ts_year_month = DATE_FORMAT(fecha,'%Y%m');
-- Actualizar la definición de la nueva columna
ALTER TABLE `test` MODIFY `ts_year_month` int(11) NOT NULL;
-- Añadir el nuevo campo al índice
ALTER TABLE `test`
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`, `ts_year_month`);
-- Crear trigger que actualice la nueva columna tras cada insert
CREATE TRIGGER `update_ts_year_month` BEFORE INSERT ON `test`
FOR EACH ROW SET NEW.ts_year_month = DATE_FORMAT(NEW.fecha,'%Y%m');
-- Crear partición mensual
ALTER TABLE test PARTITION BY HASH (`ts_year_month`) PARTITIONS 24;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment