无法删除或更新父行:外键约束失败错误

时间:2016-03-10 13:39:19

标签: mysql foreign-keys cascading-deletes drop-table

我正在尝试使用以下命令删除表appusers:

drop table appusers;

我收到以下错误:

Cannot delete or update a parent row: a foreign key constraint fails

这是我桌子的计划。

CREATE TABLE appUsers (
  uid INT PRIMARY KEY AUTO_INCREMENT,
  fullName VARCHAR(80) NOT NULL,
  email VARCHAR(100) NOT NULL,
  password VARCHAR(100) NOT NULL,
  Gender VARCHAR(7) NOT NULL,  /*["Male", "Female"]*/
  Country VARCHAR(150) NOT NULL,
  Bdate date NOT NULL, 
  Status VARCHAR(25) NOT NULL, /*["Single", "In Relationship", "Merried", "Divorced", "Widow"]*/  /*check married!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
  Religion VARCHAR(25) NOT NULL, /*["Jewish", "Christian", "Muslim", "Atheist", "Other"]*/
  ReligionStrength INT(1) NOT NULL, /*0-5*/
  PoliticalView VARCHAR(25) NOT NULL, /*["Left Wing","Center","Right Wing"]*/
  Occupation VARCHAR(25) NOT NULL, /*["Unemployed","White Collar","Blue Collar","Student", "Independent"]*/
  Volunteering VARCHAR(25) NOT NULL,  /*["Yes", "No"]*/
  Donating VARCHAR(25) NOT NULL,  /*["Yes", "No"]*/
  Economy VARCHAR(25) NOT NULL, /*["Poor","Middle Class","Rich"]*/
  EducationalYears INT(2) NOT NULL
);

我有下表

CREATE TABLE Accelerometer(
  id INT PRIMARY KEY AUTO_INCREMENT,
  uid INT NOT NULL,
  sampleTime timestamp(2) NOT NULL,
  data VARCHAR(100) NOT NULL,
  FOREIGN KEY (uid) REFERENCES appUsers(uid) ON DELETE CASCADE 
);  

据我所知,如果删除表appusers,也应该删除Accelerometer表, 我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

ON DELETE CASCADE仅适用于数据,而不适用于元数据。

=>

 Alter TABLE Accelerometer drop FOREIGN KEY (uid);

然后只有

drop table appusers;

答案 1 :(得分:0)

我意识到这已经陈旧了一段时间并且已经选择了答案,但是允许外键为NULL然后选择ON DELETE SET NULL的替代方法如何。

以下内容可能很适合您:

ALTER TABLE 'Accelerometer' 
DROP FOREIGN KEY 'uid_fk';

ALTER TABLE 'Accelerometer'
ADD CONSTRAINT 'uid_fk' FOREIGN KEY ('uid') REFERENCES 'appUsers' ('uid') ON 
UPDATE CASCADE ON DELETE SET NULL;`

我个人建议同时使用ON UPDATE CASCADEON DELETE SET NULL以避免不必要的复杂情况,但是您的设置可能会采用不同的方法。

希望这有帮助。