Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

MySQL 테이블에서 중복 데이터를 삭제하고 한 행만 남기는 방법

MySQL 테이블의 중복 데이터 제거하기

MySQL 테이블에 동일한 데이터가 여러 번 저장되어 있을 때, 임시 테이블(temporary table)을 활용하면 중복을 손쉽게 제거하고 각 데이터를 한 행씩만 남길 수 있습니다.

중복 제거 절차

전체 과정은 다음 네 단계로 진행됩니다.

  1. DISTINCT 키워드를 사용해 중복이 제거된 데이터로 임시 테이블을 생성합니다.
  2. TRUNCATE 명령으로 원본 테이블의 모든 데이터를 삭제합니다.
  3. 임시 테이블의 데이터를 원본 테이블에 다시 삽입합니다.
  4. 임시 테이블을 삭제합니다.
create table anytemporaryTableName as select distinct yourColumnName1, yourColumnName2 from yourTableName;
truncate table yourTableName;
insert into yourTableName(yourColumnName1, yourColumnName2) select yourColumnName1, yourColumnName2 from yourtemporaryTableName;
drop table yourtemporaryTableName;

예제: 실습용 테이블 생성

먼저 실습에 사용할 테이블을 만들어 보겠습니다.

mysql> create table demo39
-> (
-> user_id int,
-> user_name varchar(20)
-> );
Query OK, 0 rows affected (0.74 sec)

중복 데이터 삽입

INSERT 명령으로 의도적으로 중복된 레코드를 입력합니다.

mysql> insert into demo39 values(10,'John');
Query OK, 1 row affected (0.19 sec)

mysql> insert into demo39 values(10,'John');
Query OK, 1 row affected (0.13 sec)

mysql> insert into demo39 values(11,'David');
Query OK, 1 row affected (0.20 sec)

mysql> insert into demo39 values(11,'David');
Query OK, 1 row affected (0.17 sec)

현재 데이터 확인

SELECT 문으로 테이블을 조회하면 동일한 레코드가 두 개씩 저장되어 있는 것을 확인할 수 있습니다.

mysql> select *from demo39;
+---------+-----------+
| user_id | user_name |
+---------+-----------+
|      10 | John      |
|      10 | John      |
|      11 | David     |
|      11 | David     |
+---------+-----------+
4 rows in set (0.00 sec)

중복 삭제 쿼리 실행

다음 쿼리를 순서대로 실행하면 중복 데이터가 제거됩니다.

mysql> create table temporaryTable as select distinct user_id, user_name from demo39;
Query OK, 2 rows affected (1.39 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> truncate table demo39;
Query OK, 0 rows affected (2.30 sec)

mysql> insert into demo39(user_id, user_name) select user_id, user_name from temporaryTable;
Query OK, 2 rows affected (0.16 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> drop table temporaryTable;
Query OK, 0 rows affected (1.01 sec)

최종 결과 확인

다시 SELECT 문으로 조회하면 각 데이터가 한 행씩만 남아 있는 것을 확인할 수 있습니다.

mysql> select *from demo39;
+---------+-----------+
| user_id | user_name |
+---------+-----------+
|      10 | John      |
|      11 | David     |
+---------+-----------+
2 rows in set (0.00 sec)

마무리

이처럼 임시 테이블과 DISTINCT를 활용하면 복잡한 조건 없이도 중복 데이터를 깔끔하게 정리할 수 있습니다. 다만 TRUNCATE는 테이블의 모든 데이터를 삭제하는 작업이므로, 대용량 테이블이나 운영 환경에서는 작업 전 반드시 데이터를 백업하고 진행하는 것이 안전합니다.