반응형
만들어진 테이블들:
mysql> create table DEPARTMENT (
    -> DEPT_CD varchar(10) not null,
    -> NAME varchar(30) not null,
    -> PHONE int(11) not null,
    -> primary key(DEPT_CD)
    -> );

desc RESERVATION;
+----------------+-------------+------+-----+---------+-------+
| Field          | Type        | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| RESERVATION_ID | varchar(10) | NO   | PRI | NULL    |       |
| PATIENT        | int(13)     | NO   | MUL | NULL    |       |
| DEPARTMENT     | varchar(10) | NO   | MUL | NULL    |       |
| DOCTOR         | varchar(5)  | NO   | MUL | NULL    |       |
| DATE           | varchar(10) | NO   |     | NULL    |       |
| TIME           | varchar(10) | NO   |     | NULL    |       |
| TYPE           | varchar(20) | NO   |     | NULL    |       |
| GRANTED        | varchar(10) | NO   |     | NO      |       |
+----------------+-------------+------+-----+---------+-------+



발생한 에러:
mysql> alter table RESERVATION drop column DEPARTMENT;
ERROR 1025 (HY000): Error on rename of '.\db_project\#sql-d0_2' to '.\db_project\reservation' (errno: 150)



또다른 시도:
mysql> alter table RESERVATION drop foreign key DEPARTMENT;
ERROR 1025 (HY000): Error on rename of '.\db_project\#sql-d0_2' to '.\db_project\reservation' (errno: 152)


이 두 경우에 대한 문제의 원인분석:
(1) 일단 foreign key constraint부터 지운 후에 drop column을 하는 것이 정상적인 순서이다.
(2) 그런데 foreign key constraint를 내가 테이블 생성할 때에 지정해 주지 않았다.
(3) 따라서 내부적으로 MySQL이 직접 정해준 foreign key constraint의 이름을 알아내야 한다.


마지막으로 foreign key와 관려하여 에러난 상황을 자세히 보고 싶을 때:
mysql> SHOW INNODB STATUS;


그러면 중간쯤에서 아래와 같은 자세한 설명을 볼 수 있고, 거기서 contraint name을 찾을 수 있다.
------------------------
LATEST FOREIGN KEY ERROR
------------------------
091130 21:10:55 Error in foreign key constraint of table db_project/reservation:

there is no index in the table which would contain
the columns as the first columns, or the data types in the
table do not match the ones in the referenced table
or one of the ON ... SET NULL columns is declared NOT NULL. Constraint:
,
  CONSTRAINT "reservation_ibfk_2" FOREIGN KEY ("DEPARTMENT") REFERENCES "departm
ent" ("DEPT_CD") ON DELETE CASCADE


이제 foreign key constraint와 column name을 차례대로 지워주면 된다.
mysql> alter table reservation drop foreign key reservation_ibfk_2;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table reservation drop column DEPARTMENT;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

반응형
블로그 이미지

Bryan_

,
반응형
(예) user 테이블에 있는 h_id 필드를 home 테이블의 기본키인 home_id와 외래키로 연결하고자 할 때:

mysql> ALTER TABLE user ADD CONSTRAINT
       -> h_id FOREIGN KEY(h_id)
       -> REFERENCES home(home_id) ON DELETE CASCADE ON UPDATE CASCADE;



반응형
블로그 이미지

Bryan_

,