MySql: 使用左连接从多个表中删除
MySql: delete from multiple tables using left join
我有这个表:
- 订单:OrderId、UserId
- 订单商品:订单号、价格
OrderItems.OrderId 上有外键,有可能没有订单项。我想删除所有订单并为某些用户订购 ietms。这个 sql with inner join 工作正常:
DELETE o, oi
FROM Orders o
JOIN OrderItems oi ON o.OrderId = oi.OrderId
WHERE o.UserId = 11
但它不会删除没有订单项的订单(内部联接)。但是 sql 使用左连接查询
DELETE o, oi
FROM Orders o
LEFT JOIN OrderItems oi ON o.OrderId = oi.OrderId
WHERE o.UserId = 11
抛出错误
cannot update or delete parent row.
怎么了?是否可以在一次查询中删除用户的所有订单(有商品和无商品)?
Here解释为
If you use a multiple-table DELETE statement involving InnoDB tables for which there are foreign key constraints, the MySQL optimizer might process tables in an order that differs from that of their parent/child relationship. In this case, the statement fails and rolls back. Instead, you should delete from a single table and rely on the ON DELETE capabilities that InnoDB provides to cause the other tables to be modified accordingly
那我就用后续删除吧
我有这个表:
- 订单:OrderId、UserId
- 订单商品:订单号、价格
OrderItems.OrderId 上有外键,有可能没有订单项。我想删除所有订单并为某些用户订购 ietms。这个 sql with inner join 工作正常:
DELETE o, oi
FROM Orders o
JOIN OrderItems oi ON o.OrderId = oi.OrderId
WHERE o.UserId = 11
但它不会删除没有订单项的订单(内部联接)。但是 sql 使用左连接查询
DELETE o, oi
FROM Orders o
LEFT JOIN OrderItems oi ON o.OrderId = oi.OrderId
WHERE o.UserId = 11
抛出错误
cannot update or delete parent row.
怎么了?是否可以在一次查询中删除用户的所有订单(有商品和无商品)?
Here解释为
If you use a multiple-table DELETE statement involving InnoDB tables for which there are foreign key constraints, the MySQL optimizer might process tables in an order that differs from that of their parent/child relationship. In this case, the statement fails and rolls back. Instead, you should delete from a single table and rely on the ON DELETE capabilities that InnoDB provides to cause the other tables to be modified accordingly
那我就用后续删除吧