[英]Delete records from parent table and child table in mysql
I want to delete record from table with foreign key. 我想用外键从表中删除记录。 Table structure is:
表结构为:
CREATE TABLE `employees` (
`employeeNumber` int(11) NOT NULL,
`lastName` varchar(50) NOT NULL,
`firstName` varchar(50) NOT NULL,
`extension` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
`officeCode` varchar(10) NOT NULL,
`reportsTo` int(11) DEFAULT NULL,
`jobTitle` varchar(50) NOT NULL,
PRIMARY KEY (`employeeNumber`),
KEY `reportsTo` (`reportsTo`),
KEY `officeCode` (`officeCode`),
CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`reportsTo`) REFERENCES `employees` (`employeeNumber`),
CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES `offices` (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Second table: 第二张表:
Create Table">CREATE TABLE `offices` (
`officeCode` varchar(10) NOT NULL,
`city` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`state` varchar(50) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`postalCode` varchar(15) NOT NULL,
`territory` varchar(10) NOT NULL,
PRIMARY KEY (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I'm facing this error: 我遇到这个错误:
delete from offices where officeCode=7 Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`classicmodels`.`employees`, CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES `offices` (`officeCode`)) 0.093 sec
从officeCode = 7的办公室删除,错误代码:1451。无法删除或更新父行:外键约束失败(`classicmodels`.employees`,CONSTRAINT`employees_ibfk_2` FOREIGN KEY(`officeCode`)参考`offices( `officeCode`))0.093秒
You have one option to delete child table entry first then after delete to master table. 您可以选择先删除子表条目,然后再删除到主表。 like this
像这样
delete from employees where officeCode=7
delete from offices where officeCode=7
Since employees.officeCode
is declared as a foreign key to offices.officeCode
, all office codes that are used in the employees
table have to exist in the offices
table. 由于将
employees.officeCode
声明为offices.officeCode
的外键,因此employees
表中使用的所有office代码都必须存在于offices
表中。 You can't delete an office if there are any employees in that office. 如果该办公室有任何员工,则无法删除该办公室。
You either have to delete those employees first, or you can tell MySQL to do this automatically by adding the ON DELETE CASCADE
option to the FOREIGN KEY
constraint. 您要么必须先删除这些雇员,要么可以通过将
ON DELETE CASCADE
FOREIGN KEY
约束添加ON DELETE CASCADE
选项来告诉MySQL自动执行此操作。
If you allow employees.officeCode
to be NULL
, you could also use ON DELETE SET NULL
to leave the employees there, but set their officeCode
to NULL
. 如果允许
employees.officeCode
为NULL
,则还可以使用ON DELETE SET NULL
来将员工留在此处,但将其officeCode
设置为NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.