天天看點

mysql删除主鍵

執行語句:

alter table test.sc drop primary key;

報錯資訊為:

ERROR 1025 (HY000): Error on rename of '.\test\#sql-12fc_2b' to '.\test\sc' (errno: 150 - Foreign key constraint is incorrectly formed);

試了半天無果,然後我使用:

show create table test.sc;

語句檢視建表語句,結構如下:

mysql删除主鍵
CREATE TABLE `sc` (
  `Sno` varchar(255) NOT NULL,
  `Cno` varchar(255) NOT NULL,
  `Score` float NOT NULL,
  PRIMARY KEY (`Sno`) USING BTREE,
  KEY `Cno` (`Cno`),
  CONSTRAINT `sc_ibfk_1` FOREIGN KEY (`Sno`) REFERENCES `student` (`Sno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
           

原因找到,我想删除主鍵Sno,但是主鍵同時又是外鍵參照了student表的Sno列,是以我先将外鍵删除,再将主鍵删除。成功。

alter table test.sc drop foreign key sc_ibfk_1;
alter table test.sc drop primary key;
           

注意删除外鍵的時候用的是一個系統生成的别名。