¿Cómo puedo combinar dos tablas MySQL?


¿Cómo puedo combinar dos tablas MySQL que tienen la misma estructura?

Las claves principales de las dos tablas chocarán, así que lo he tenido en cuenta.

Author: dakab, 2009-04-07

6 answers

También puedes probar:

INSERT IGNORE
  INTO table_1 
SELECT *
  FROM table_2
     ;

Que permite que las filas de table_1 sustituyan a las de table_2 que tienen una clave primaria coincidente, mientras que todavía se insertan filas con nuevas claves primarias.

Alternativamente,

REPLACE
   INTO table_1
 SELECT *
   FROM table_2
      ;

Actualizará las filas que ya están en table_1 con la fila correspondiente de table_2, mientras inserta filas con nuevas claves primarias.

 112
Author: fcw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-07 13:04:18

Depende de la semántica de la clave primaria. Si es solo autoincremento, entonces use algo como:

insert into table1 (all columns except pk)
select all_columns_except_pk 
from table2;

Si PK significa algo, debe encontrar una manera de determinar qué registro debe tener prioridad. Puede crear una consulta select para encontrar duplicados primero (ver respuesta de cpitis). Luego elimine los que no desea conservar y use el inserto anterior para agregar registros que permanecen.

 36
Author: Milan Babuškov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:20
INSERT
INTO    first_table f
SELECT  *
FROM    second_table s
ON DUPLICATE KEY
UPDATE
        s.column1 = DO_WHAT_EVER_MUST_BE_DONE_ON_KEY_CLASH(f.column1)
 21
Author: Quassnoi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-05 13:32:14

Si necesita hacerlo manualmente, una vez:

Primero, combine en una tabla temporal, con algo como:

create table MERGED as select * from table 1 UNION select * from table 2

Luego, identifique las restricciones de clave primaria con algo como

SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1

Donde PK es el campo de clave primaria...

Resuelve los duplicados.

Cambie el nombre de la tabla.

[edited-removed brackets in the UNION query, which was causing the error in the comment below]

 15
Author: Cătălin Pitiș,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-28 11:34:42

No es tan complicado como parece.... Simplemente deje la clave primaria duplicada fuera de su consulta.... esto funciona para mí !

INSERT INTO
  Content(
    `status`,
    content_category,
    content_type,
    content_id,
    user_id,
    title,
    description,
    content_file,
    content_url,
    tags,
    create_date,
    edit_date,
    runs
  )
SELECT `status`,
  content_category,
  content_type,
  content_id,
  user_id,
  title,
  description,
  content_file,
  content_url,
  tags,
  create_date,
  edit_date,
  runs
FROM
  Content_Images
 6
Author: Bill Warren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-17 18:57:52

Podrías escribir un script para actualizar los FK por ti.. echa un vistazo a este blog: http://multunus.com/2011/03/how-to-easily-merge-two-identical-mysql-databases /

Tienen un script inteligente para usar las tablas information_schema para obtener las columnas" id":

SET @db:='id_new'; 

select @max_id:=max(AUTO_INCREMENT) from information_schema.tables;

select concat('update ',table_name,' set ', column_name,' = ',column_name,'+',@max_id,' ; ') from information_schema.columns where table_schema=@db and column_name like '%id' into outfile 'update_ids.sql';

use id_new
source update_ids.sql;
 0
Author: TimoSolo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-20 13:35:19