|
我正在尝试从多个表中删除。这是我的桌子的样子
6 z( f/ F, J, Q0 e5 | A_has_B ---- B ---- C_has_B
; v( a, X3 \. h# Z(many to many) (many to many)# b8 O+ F" y* N! R5 A. ?7 p# k
给定B中的记录ID,我试图删除A_has_B,B和C_has_B中的所有行。我将MySQL与innodb存储引擎配合使用,并为A_has_B和C_has_B定义了引用B中ID的外键。& z" A/ G% x6 e/ D
我正在尝试执行删除操作,如下所示:' z- G# P! K5 U) Z# v' s( }0 |
DELETE A_has_B.*, C_has_B.*, B.*
) {8 b0 W- _- M" q% ] j- [* M, @FROM3 Y& h7 \7 J, D$ C3 L
A4 N1 C$ m: E8 Z- ~' X9 x
join
# N7 z! o' Y: V( C! d+ I; Z: u8 w. RB, O8 s+ V% I* C$ v# a. r
on (B.B_id = A.B_id)7 M' y: h4 ^# i- \* [% [
join
0 P: }0 g+ s2 Z; M# m' uC
1 m8 T8 L0 T4 B7 mon (C.B_id = B.B_id)9 [- F8 {7 I6 Y- H
where B.B_id IN(1,2, 4);
. d7 e |" i8 v4 c s5 s9 y问题是当我执行查询时,mysql抱怨:2 C! g! }* b1 a9 @
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`db`.`C`, CONSTRAINT `fk_C` FOREIGN KEY (`B_id`) REFERENCES `B` (`B_id`) ON DELETE NO ACTION ON UPDATE NO)
F$ E% Z9 s. J7 B4 `. z% e' d, J* e我该如何解决这个问题?. c. N! K5 U; D" q* |3 y
- ^! b0 I! j D解决方案:4 w3 C; A* J6 F9 U
8 b. C+ y2 R& m0 i, T s8 @
4 E1 f' e7 W1 ~" `; |& E+ b6 H, `
' b3 P, q- n: S3 D* N; b0 \
最简单的方法是分别从每个表中删除:
, K! D1 X; l+ c8 R c/ n! f-- Remove all connections from A which reference6 z C1 y. v% E+ \8 R5 \
-- the B-rows you want to remove; s; O3 A% T6 l- |/ V i. G! X/ `
DELETE FROM A_has_B2 H0 l6 r+ r$ L
WHERE B_id IN (1,2,4);; ^6 K8 V/ K/ _$ g
-- Remove all connections from C which reference
3 k. ^$ u, d4 u- H& i; y8 S& G. s-- the B-rows you want to remove
5 z; l" I! r$ T. v7 I2 WDELETE FROM C_has_B) c( z" N% A- w; `5 S4 S7 j m- z1 I+ }
WHERE B_id IN (1,2,4);
+ A0 W2 ^* D( o-- Finally remove the B-rows8 H6 L7 |1 `4 P3 t/ a5 z
DELETE FROM B
' C i9 @4 [# KWHERE B_id IN (1,2,4);
( K. o1 e4 J1 ]/ E4 k0 AMySQL还允许您在一条语句中从多个表中删除。但是无法控制删除的顺序。从手册:+ e% I5 q8 J4 {+ V' h) H- m0 R* [! N" V
4 b# c8 W3 `# f5 y" w1 `$ Z Z& f }2 R如果您使用涉及具有外键约束的InnoDB表的多表DELETE语句,则MySQL优化器可能以与其父/子关系不同的顺序处理表。在这种情况下,该语句将失败并回滚。相反,您应该从单个表中删除,并依靠InnoDB提供的ON# h0 R- _1 W/ Q. n B) c
DELETE功能来相应地修改其他表。 |
|