두 개의 MySQL 테이블을 병합하려면 어떻게해야합니까?
동일한 구조를 가진 두 개의 MySQL 테이블을 병합하려면 어떻게해야합니까?
두 테이블의 기본 키가 충돌하므로이를 고려했습니다.
다음을 시도해 볼 수도 있습니다.
INSERT IGNORE
INTO table_1
SELECT *
FROM table_2
;
이를 통해 table_1의 해당 행이 일치하는 기본 키가있는 table_2의 행을 대체하면서 새 기본 키가있는 행을 계속 삽입 할 수 있습니다.
또는
REPLACE
INTO table_1
SELECT *
FROM table_2
;
새로운 기본 키가있는 행을 삽입하는 동안 table_1에 이미있는 행을 table_2의 해당 행으로 업데이트합니다.
기본 키의 의미에 따라 다릅니다. 자동 증가 인 경우 다음과 같이 사용하십시오.
insert into table1 (all columns except pk)
select all_columns_except_pk
from table2;
PK가 의미하는 경우 어떤 레코드가 우선 순위를 가져야하는지 결정하는 방법을 찾아야합니다. 먼저 중복을 찾기 위해 선택 쿼리를 만들 수 있습니다 ( cpitis의 답변 참조 ). 그런 다음 유지하지 않으려는 레코드를 제거하고 위의 삽입을 사용하여 남아있는 레코드를 추가하십시오.
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)
수동으로 수행해야하는 경우 한 번 :
먼저 다음과 같은 임시 테이블을 병합합니다.
create table MERGED as select * from table 1 UNION select * from table 2
그런 다음 다음과 같이 기본 키 제약 조건을 식별하십시오.
SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1
PK가 기본 키 필드 인 경우 ...
중복을 해결하십시오.
테이블 이름을 바꿉니다.
[편집 됨-UNION 쿼리에서 제거 된 대괄호로 인해 아래 주석에 오류가 발생했습니다.]
들리는 것만 큼 복잡하지 않습니다 .... 쿼리에서 중복 된 기본 키를 남겨 두십시오 .... 이것은 나를 위해 작동합니다!
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
You could write a script to update the FK's for you.. check out this blog: http://multunus.com/2011/03/how-to-easily-merge-two-identical-mysql-databases/
They have a clever script to use the information_schema tables to get the "id" columns:
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;
참고URL : https://stackoverflow.com/questions/725556/how-can-i-merge-two-mysql-tables
'program tip' 카테고리의 다른 글
문자열 열의 각 행에서 주어진 문자의 발생 횟수를 계산하는 방법은 무엇입니까? (0) | 2020.09.05 |
---|---|
Travis-CI를 C # 또는 F #과 함께 사용하는 방법 (0) | 2020.09.05 |
git push local branch with same name as remote tag (0) | 2020.09.05 |
d3 축 라벨링 (0) | 2020.09.05 |
NodeJS의 Mongo 데이터베이스에 삽입 된 문서의 _id를 가져옵니다. (0) | 2020.09.05 |