如何使用JOIN从MySQL中的多个表中删除?

时间:2018-01-22 14:20:47

标签: mysql

我试图运行此删除脚本:

DELETE auth, cust
FROM customer cust 
JOIN authentication_token auth ON auth.customer_id = cust.id
WHERE cust.email = 'my@email.com';

我收到错误:

Cannot delete or update a parent row: a foreign key constraint fails (`my_table`.`authentication_token`, CONSTRAINT `authentication_token_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`))

我试图更改DELETE语句(cust,auth)的顺序,并且我尝试更改了联接的顺序,但仍然是同样的错误。

这可能,还是我必须暂时禁用约束?

表格结构:

CREATE TABLE `customer` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) DEFAULT NULL,
  `firstName` varchar(255) DEFAULT NULL,
  `lastName` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `passwordSalt` varchar(255) DEFAULT NULL,
  `phoneNumber` varchar(255) DEFAULT NULL,
  `addressLine1` varchar(255) DEFAULT NULL,
  `addressLine2` varchar(255) DEFAULT NULL,
  `city` varchar(255) DEFAULT NULL,
  `country` varchar(255) DEFAULT NULL,
  `county` varchar(255) DEFAULT NULL,
  `postCode` varchar(255) DEFAULT NULL,
  `registeredOn` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `authentication_token` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `value` varchar(255) DEFAULT NULL,
  `createdOn` datetime DEFAULT NULL,
  `customer_id` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `customer_id` (`customer_id`),
  CONSTRAINT `authentication_token_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`)
)

2 个答案:

答案 0 :(得分:1)

更改表格定义:

CREATE TABLE `authentication_token` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `value` varchar(255) DEFAULT NULL,
  `createdOn` datetime DEFAULT NULL,
  `customer_id` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `customer_id` (`customer_id`),
  CONSTRAINT `authentication_token_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) ON DELETE CASCADE
)

然后运行这个SQL:

DELETE FROM cust WHERE cust.email = 'my@email.com';

当您从cust删除记录时,authentication_token中的相关记录将自动删除。

答案 1 :(得分:0)

  

无法删除或更新父行

这意味着,您无法更新/删除父表,因为参考仍然存在于其他一些子表中。

如果您想从两个表中删除,那么最佳解决方案是更改您的表以添加

ON CASCADE DELETE

它将确保删除所有引用行。

CONSTRAINT `authentication_token_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) ON CASCADE DELETE